In the "Ticket" model:
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
public function getSupervisor()
{
return $this->hasOne(User::className(), ['id' => 'supervisor_id']);
In the "TicketSearch" model:
$query->joinWith(['user','supervisor']);
$query
->andFilterWhere(['like', 'user.surname', $this->user_id])
->andFilterWhere(['like', 'user.surname', $this->supervisor_id]
If I try to search supervisor, get this error:
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%'
I have tried to change name user table:
public function getSupervisor()
{
return $this->hasOne(User::className(), ['id' => 'supervisor_id'])
->from(User::tableName() . 'u2');
}
But this error returned:
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%'
You missed space before alias. Should be:
public function getSupervisor()
{
return $this->hasOne(User::className(), ['id' => 'supervisor_id'])
->from(User::tableName() . ' u2');
}
You can also specify it as array key:
public function getSupervisor()
{
return $this->hasOne(User::className(), ['id' => 'supervisor_id'])
->from(['u2' => User::tableName()]);
}
Or even in joinWith()
with this relation:
->joinWith([
'supervisor' => function ($query) {
/* @var $query \yii\db\ActiveQuery */
$query->from(User::tableName() . ' u2');
// or $query->from(['u2' => User::tableName()]);
},
]);
Official documentation: