Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2: how to use priority with andWhere and orWhere?

I have a Yii2 query but I have the problem with the orWhere Yii sentence.

I need persons where:

  • age is under 21.

  • OR age is above 21 AND first name is John.

This is my code. I don't know how to use parenthesis for priority in Yii2:

Persons::find()
    ->select([Persons::tableName().".[[first_name]]"])
    ->where(['<', 'age', 21])
    ->orWhere(['>', 'age', 21])
    ->andwhere([Persons::tableName().".[[first_name]]" => 'John'])
like image 760
Roby Sottini Avatar asked Oct 29 '25 19:10

Roby Sottini


1 Answers

The easiest way would be to use one array with proper nesting:

Persons::find()
    ->select([Persons::tableName() . ".[[first_name]]"])
    ->where([
        'or',
        ['<', 'age', 21],
        [
            'and',
            ['>', 'age', 21],
            [Persons::tableName() . ".[[first_name]]" => 'John'],
        ],
    ]);

andwhere() and orWhere() are always appended new condition to the existing conditions, so you will get something like:

(((<first condition>) AND <second condition>) OR <third condition>)
like image 196
rob006 Avatar answered Nov 01 '25 09:11

rob006



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!