yii2 leftjoin 查询生成器

yii2 leftjoin query builder

我在用户和员工之间有一个 relation/hierarchy:员工始终是用户,但用户也可以是学生或管理员。现在,通过查询,我只想获取用户中 is_disabled 字段等于 false 的员工记录。我尝试了以下但给了我错误:

staff hasn't is_disabled field

没错,该字段仅在用户 table 中。

用户

 * @property int $id
 * @property string $username
 * @property string password

员工

 * @property int $id
 * @property string $cellphone
 * @property string $phone
 * @property string $link
 * @property User $id0

搜索人员

public function search($params)
{
    $query = Staff::find()
    ->leftJoin('user', '`user`.`id` = `staff`.`id`')
    ->where(['user.is_disabled' => false);
}

连接错误,外键应该是id0.

public function search($params)
{
    $query = Staff::find()
    ->leftJoin('user', 'user.id = staff.id0')
    ->where(['user.is_disabled' => false);
}

您还可以在 Staff 模型中创建关系:

public function getUser(){
    return $this->hasOne(User::className(), ['id' => 'id0']);
}

并编辑查询:

$query = Staff::find()
  ->joinWith('user')
  ->where(['user.is_disabled' => false)];