简体   繁体   中英

Yii2 SQL query grouping OR with AND

Good day.

I am relatively new to yii2.

What am I trying is this sort of SQL query:

SELECT * FROM table WHERE a=1 AND (b=1 OR b=2)

How do I write such query via yii2 query builder?

You need to use orWhere() , andWhere() and where() functions.

the "or" and "and" words are the type of union it made with all the previous where conditions

so, this query:

Table::find()->where('b=1')->orWhere('b=2')->andWhere('a=1')->all();

Make something like this:

select * from Table where (((b=1) or b=2) and a=1)

The all() function tell yii2 to select al records its founds

Note: this code dont work, its just and example.

This can be done like this:

$model = User::find()
        ->where('a = :a', [':a' => 1])
        ->andWhere('b = :b1 or b = :b2', [':b1' => 1, ':b2'=> 2])
        ->all();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM