Yii2:如何将优先级与 andWhere 和 orWhere 一起使用?

Yii2: how to use priority with andWhere and orWhere?

我有一个 Yii2 查询,但是 orWhere Yii 语句有问题。

我需要以下人员:

这是我的代码。我不知道如何在 Yii2 中使用括号来表示优先级:

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

最简单的方法是使用一个具有适当嵌套的数组:

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

andwhere()orWhere() 总是在现有条件上附加新条件,所以你会得到类似:

(((<first condition>) AND <second condition>) OR <third condition>)

您可以使用以下代码进行查询:

Persons::find()
    ->select(["first_name"])
    ->where(['<', 'age', 21])
    ->orWhere("age > 21 AND first_name LIKE 'John'")
    ->all();

根据以上代码生成的查询:

SELECT `first_name` FROM `persons` WHERE (`age` < 21) OR (age > 21 AND first_name LIKE 'John').