Join a relation and override the default where condition from the relation.
NavItem::find()
->select(['cms_nav_item.title', 'timestamp_update', 'update_user_id', 'nav_id'])
->joinWith(['updateUser' => function ($q) {
$q->select(['firstname', 'lastname', 'id'])->where([]);
}, 'nav'])
->where(['cms_nav.is_deleted' => false])
->limit(10)
->orderBy(['timestamp_update' => SORT_DESC])
->asArray(true)
->all();
The relation inside the model:
public function getUpdateUser()
{
return $this->hasOne(User::class, ['id' => 'update_user_id']);
}
The find method from the User model:
public static function find()
{
return parent::find()->where(['is_deleted' => false]);
}
So the $q->select(['firstname', 'lastname', 'id'])->where([]); will override where(['is_deleted' => false]);.
btw: I'm sure there is also a better solution for this problem, but it was working in 2.0.13 so i thought it makes sense to report.
Returns the array with results.
In the current dev-master the $q->select(['firstname', 'lastname', 'id'])->where([]); does not override the relation where condition anymore. this will raise an exception:
"SQLSTATE[42000]: Syntax error or access violation: 1064
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 ')) AND (`id` IN ('1', '0'))' at line 1
The SQL being executed was:
SELECT `firstname`, `lastname`, `id`
FROM `admin_user`
WHERE (()) AND (`id` IN ('1', '0'))"
| Q | A
| ---------------- | ---
| Yii version | dev-master
| PHP version |
| Operating system |
Will handle it this evening
I thing in all previous Yii versions ->where([...]) overwritten previously used ->where(). You need use ->andWhere([...]) or ->orWhere([...]) to append where condition.
@pistej I know, but i did the overide on purpose, which does not work anymore.
Fixed, thank you for the report.
@SilverFire just installed the latest dev-master, works as expected. Thanks
Most helpful comment
Will handle it this evening