Yii2 How to perform where AND or OR condition grouping?

Vikas Chaudhary picture Vikas Chaudhary · Jul 22, 2015 · Viewed 93.2k times · Source

I am new to Yii-2 framework. How can i achieve following query in Yii-2 framework using activeQuery and models.

SELECT * FROM users AS u WHERE u.user_id IN(1,5,8) AND (u.status = 1 OR u.verified = 1) OR (u.social_account = 1 AND u.enable_social = 1)

Thanks

Answer

gouki picture gouki · Jun 17, 2017

You can try this:

//SELECT * FROM users AS u WHERE u.user_id IN(1,5,8) AND (u.status = 1 OR u.verified = 1) OR (u.social_account = 1 AND u.enable_social = 1)
$model = arname()->find()
       ->andWhere(['user_id'=>[1,5,8]])
       ->andWhere(['or',
           ['status'=>1],
           ['verified'=>1]
       ])
       ->orWhere(['and',
           ['social_account'=>1],
           ['enable_social'=>1]
       ])
       ->all();