Search code examples
activerecordyiiyii2relationship

yii hasone relation with condition


I have a hasone relation in my code,

public function getDevice(){
    return $this->hasOne(UserDevice::className(),['user_id' => 'id'])->where(['is_latest'=>true]);
}

In my query, I am trying to fetch user details.

  $query = User::find();
  $query->joinWith('device')->all();

If i am using getDevice without where condition, I am getting all users. But if I add where condition inside getDevice, I am getting users that have device details. Is there anyway to list all users with the chceking. That is I need to list all users, who has either details in device table or not


Solution

  • I have used this in my relation and it works.

    public function getDevice(){
        return $this->hasOne(UserDeviceInfo::className(),['user_id' => 'id'])->orOnCondition(['is_latest' =>1]);
    }