[英]how to represent yii relations of two foreign keys refrencing one primary key?
我如何表示該模型的關系:我們有一個包含PKey的用戶表。 用戶分為兩種類型:雇主和工人->這兩個表包含一個Fkey重發給用戶PKey。
我已經在用戶模型中編寫了類似的代碼:
public function userTypeMapper($type)
{
switch ($type) {
case 'w':
return 'Worker';
case 'e':
return 'Employer';
case 'a':
return 'Admin';
default:
return 'Employer';
return 'Guest';
}
}
/**
* @return array relational rules.
*/
public function relations()
{
$entity = $this->userTypeMapper($this->u_type);
return array(
'entity' => array(self::HAS_ONE, $entity, 'u_id'),
'projects' => array(self::HAS_MANY, 'Project', 'pr_u_id'),
);
}
這樣,雇主和工人模型之間的$ entity交替出現!
問題是它不起作用!!! 我不知道為什么在Project模型獲取所有者(在用戶中)時未設置u_type。 解釋關系時,實際上什么也沒有設置。
好了,關系函數在模型初始化時調用,它沒有任何屬性。 當你$user = new User();
您的模型User
已經建立了關系。 您必須設置所有關系:
public function relations()
{
return array(
'Worker' => array(self::HAS_ONE, 'Worker', 'u_id'),
'Employer' => array(self::HAS_ONE, 'Employer', 'u_id'),
'Admin' => array(self::HAS_ONE, 'Admin', 'u_id'),
'Guest' => array(self::HAS_ONE, 'Guest', 'u_id'),
'projects' => array(self::HAS_MANY, 'Project', 'pr_u_id'),
);
}
/**
* Get entity
*/
public function getEntity()
{
switch ($this->u_type) {
case 'w':
return $this->Worker;
case 'e':
return $this->Employer;
case 'a':
return $this->Admin;
default:
return $this->Guest;
}
}
當您想要獲取實體模型時,只需調用
$user = User::model()->findByPk($user_id);
$entity = $user->entity;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.