Yii2: join relation override inherit where

Created on 16 Feb 2018  路  5Comments  路  Source: yiisoft/yii2

What steps will reproduce the problem?

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.

What is the expected result?

Returns the array with results.

What do you get instead?

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'))"

Additional info

| Q | A
| ---------------- | ---
| Yii version | dev-master
| PHP version |
| Operating system |

important bug

Most helpful comment

Will handle it this evening

All 5 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

newscloud picture newscloud  路  3Comments

chaintng picture chaintng  路  3Comments

indicalabs picture indicalabs  路  3Comments

psfpro picture psfpro  路  3Comments

jpodpro picture jpodpro  路  3Comments