Yii2 有一个关系 link 到多个 table

Yii2 hasOne relation link to multiple table

我有 4 个 table 是代理人、供应商、操作员和票证。一张票只属于代理人、供应商或运营商之一。 我设计的ticket table有两个字段:org_typeorg_id 在 Ticket 模型 class 中,我想构建 3 个函数 getAgent、getVendor、getOperator 使用 Yii2

的 hasOne 关系

解决方案 1:

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

会失败,因为我不能使用 $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 是工单字段,而不是代理人。

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

谁能给我一个解决方案?

一个解决方案是建立另一个关系来过滤组织类型,并将其用作从代理 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')
}

通过这种方式,您可以以少量查询开销为代价获得完整的功能关系(延迟加载、连接等)
另一种方法是改变你的数据库