【发布时间】:2018-07-08 03:55:40
【问题描述】:
我有 3 个 Yii2 ActiveRecord 模型:Emplpoyee、Department 和 Organization。
Employee 必须有一个Department 或一个Organization,这是通过验证确保的(如果department_id 和organization_id 都是null 或两者都不是null,则失败)。 Department 必须有一个Organization,这是通过hasOne() 实现的标准yii2 ORM 关系。
Gii 为员工/组织关系创建了此代码:
class Employee
{
public function getOrganization()
{
return $this->hasOne(app\models\Organization::class, ['id' => 'organization_id']);
}
}
所以当我调用$employeeObject->organization时,如果SQL表中的organization_id为空,我会得到null。
我想修改这个标准的 getter 函数以返回 $this->department->organization,以便能够像这样通过魔术 getter 获得 $employee->organization:如果员工有部门 - 组织从部门获取,否则 - 通过标准关系。
更新:如果我写:
/**
* @return ActiveQuery
*/
public function getOrganization()
{
if (!is_null($this->organization_id)) {
return $this->hasOne(app\models\Organization::class, ['id' => 'organization_id']);
} elseif (!is_null($this->department)) {
return $this->department->getOrganization();
} else {
// We should not be here, but what if we are?
}
}
我如何处理与Department 或organization_id 和department_id 是null 的关系中断的情况?我该返回哪个ActiveQuery?
【问题讨论】:
-
那么问题出在哪里?您是否尝试过编写自己的吸气剂?给我们看一些代码。
-
添加了经验代码。我不明白如何处理破裂的关系?抛出异常?
-
只返回null。