Yii2 hasOne 关系链接到多个表 [英] Yii2 hasOne relation link to multiple table

查看:24
本文介绍了Yii2 hasOne 关系链接到多个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 4 个表,分别是代理、供应商、操作员和票证.一张票只属于代理商、供应商或运营商之一.我设计的工单表有两个字段:org_typeorg_id在 Ticket 模型类中,我想构建 3 个函数 getAgent、getVendor、getOperator 使用 Yii2 的 hasOne 关系

I have 4 tables are agent, vendor, operator and ticket. A ticket is belong to only one of agent, vendor or operator. I designed ticket table have two fields: org_type and org_id In Ticket model class, I want to build 3 function getAgent, getVendor, getOperator use hasOne relation of Yii2

解决方案 1:

public function getAgent()
{
    if ($this->org != Organization::ORGANIZATION_TYPE__AGENT)
        return null;
    return $this->hasOne(Agent::class, ['id' => 'org_id']);
}

会失败,因为我不能使用 $query->joinWith('agent');

will be failed because I can't use $query->joinWith('agent');

解决方案 2:

public function getAgent()
{
    return $this->hasOne(Agent::class, ['id' => 'org_id'])
        ->andWhere(['org' => Organization::ORGANIZATION_TYPE__AGENT]);
}

也失败,因为 hasOne 关系将进行此查询:select * from agent where id = 3 and org = 'agent'org 是票证字段,而不是代理.

also failed because hasOne relation will make this query: select * from agent where id = 3 and org = 'agent' but org is field of ticket, not agent.

我想在查询 joinWith 中使用这个 hasOne 关系,以便我可以在 GridView 中过滤和排序

I want to use this hasOne relation in query joinWith to I can filter and sort in GridView

谁能给我一个解决方案?

Can anyone give me a solution for this?

推荐答案

一种解决方案是使用另一种关系来过滤组织类型,并将其用作从代理表中获取记录的枢轴.

One solution is to have another relation to filter organization types and use that as pivot to grab records from agent table.

public function getOrganizationForAgent(){
    return $this->hasOne(static::class, ['id' => 'id'])
        ->andOnCondition(['org' => Organization::ORGANIZATION_TYPE__AGENT]);
}

public function getAgent(){
    return $this->hasOne(Agent::class, ['id' => 'org_id'])
        ->via('organizationForAgent')
}

通过这种方式,您可以以少量查询开销为代价获得完全正常运行的关系(延迟加载、连接等)
另一种方法是更改​​您的数据库

This way you get fully a functioning relation (lazy loading, joins, etc) at the cost of bit of query overhead
The alternative is to alter your database

这篇关于Yii2 hasOne 关系链接到多个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆