我有一个 Yii2 查询,但我遇到了 orWhere
Yii 语句的问题。
我需要以下人员:
年龄在 21 岁以下。
OR
年龄在 21 岁以上AND
名字是 John。
这是我的代码。我不知道如何在 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>)
关于Yii2:如何将优先级与 andWhere 和 orWhere 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52667334/