在“Ticket”模型中:
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
public function getSupervisor()
{
return $this->hasOne(User::className(), ['id' => 'supervisor_id']);
在“TicketSearch”模型中:
$query->joinWith(['user','supervisor']);
$query
->andFilterWhere(['like', 'user.surname', $this->user_id])
->andFilterWhere(['like', 'user.surname', $this->supervisor_id]
如果我尝试搜索主管,请收到此错误:
Not unique table/alias: 'user'
The SQL being executed was: SELECT COUNT(*) FROM `ticket` LEFT JOIN `user` ON `ticket`.`user_id` = `user`.`id` LEFT JOIN `user` ON `ticket`.`supervisor_id` = `user`.`id` WHERE `user`.`surname` LIKE '%surname4%'
我试图更改名称用户表:
public function getSupervisor()
{
return $this->hasOne(User::className(), ['id' => 'supervisor_id'])
->from(User::tableName() . 'u2');
}
但是这个错误又回来了:
You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near 'u2.`id`
WHERE `supervisor`.`surname` LIKE '%surname4%'' at line 1 The SQL being executed was:
SELECT COUNT(*) FROM `ticket` LEFT JOIN `user` ON `ticket`.`user_id` = `user`.`id` LEFT JOIN `user`u2 ON
`ticket`.`supervisor_id` = `user`u2.`id` WHERE `supervisor`.`surname` LIKE '%surname4%'
答案 0 :(得分:10)
你在别名之前错过了空间。应该是:
public function getSupervisor()
{
return $this->hasOne(User::className(), ['id' => 'supervisor_id'])
->from(User::tableName() . ' u2');
}
您也可以将其指定为数组键:
public function getSupervisor()
{
return $this->hasOne(User::className(), ['id' => 'supervisor_id'])
->from(['u2' => User::tableName()]);
}
甚至在joinWith()
中有这种关系:
->joinWith([
'supervisor' => function ($query) {
/* @var $query \yii\db\ActiveQuery */
$query->from(User::tableName() . ' u2');
// or $query->from(['u2' => User::tableName()]);
},
]);
官方文件:
答案 1 :(得分:1)
从2.0.7版开始,有alias()
方法:
public function getSupervisor()
{
return $this->hasOne(User::className(), ['id' => 'supervisor_id'])->alias('supervisor');
}