我有一个 Yii2 查询,但我对 YiiorWhere
句子有问题。
我需要以下人员:
-
年龄在21岁以下。
-
OR
年龄在21岁以上AND
名字是约翰。
这是我的代码。我不知道如何在 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').