Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 How to perform where AND or OR condition grouping?

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

like image 395
Vikas Chaudhary Avatar asked Jul 22 '15 08:07

Vikas Chaudhary


People also ask

How to write SQL query in Yii2?

Call yii\db\QueryBuilder to generate a SQL statement based on the current construct of yii\db\Query; Create a yii\db\Command object with the generated SQL statement; Call a query method (e.g. queryAll()) of yii\db\Command to execute the SQL statement and retrieve the data.

What is Query Builder in Yii2?

The Yii Query Builder provides an object-oriented way of writing SQL statements. It allows developers to use class methods and properties to specify individual parts of a SQL statement.

Is null in Yii2 query?

Yii2 will use "IS NULL" if the $values === null , but in case the value is supplied as an array, and one of those array elements is null, it will not get any special treatment, resulting in the query never matching any records with NULL value.

What is Query Builder in PHP?

The database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application, and works on all supported database systems.


1 Answers

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(); 
like image 88
gouki Avatar answered Sep 19 '22 19:09

gouki