Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 Active record query multiple where clause from array

Tags:

yii2

Yii2's index page's default data provider is like following:

$dataProvider = new ActiveDataProvider([
    'query' => ModelName::find(),
]); 

Now, I've got an array like $arr = [1, 2, 4, 6];

I want to add a where clause like:

WHERE parentId=1 OR parentId=2 OR parentId=4 OR parentId=6

How can I do that?

like image 204
Pingu Kutu Avatar asked Jun 16 '15 06:06

Pingu Kutu


1 Answers

Can be done like this:

$query = ModelName::find()->where(['parentId' => $arr]);

$dataProvider = new ActiveDataProvider([
    'query' => $query,
]);

When you pass an array to where, Yii automatically transforms it into IN condition.

So generated SQL conditional part will be WHERE parentId IN (1, 2, 4, 6);.

It's equivalent to your mentioned condition with OR.

like image 83
arogachev Avatar answered Nov 04 '22 22:11

arogachev