Yii2 不唯一 table/alias: 'user'

Yii2 Not unique table/alias: 'user'

在"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%'

我试过更改用户名 table:

    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%'

您在别名前遗漏了 space。应该是:

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()]);
    },
]);

官方文档:

从版本 2.0.7 开始有 alias() 方法:

public function getSupervisor()
{
    return $this->hasOne(User::className(), ['id' => 'supervisor_id'])->alias('supervisor');
}