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

标签 yii2 where query-builder

我有一个 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/

相关文章:

php - Symfony 2.7 EntityType -> StartDateTime 和 EndDateTime 之间的 QueryBuilder 或 null

yii2 - 将 Logo 和标题添加到 NavBar (Yii2)

mysql - Yii2 中的子查询 order by 和 group by

MySQL - 在哪里或?

php - Laravel 查询生成器,基于条件的位置?

mysql - 将 BINARY 运算符添加到 CakePHP 3 查询

php - Yii2:从提交按钮重定向到特定操作

javascript - Kartik Yii2 Number - 从扩展中获取值(value)

带有 WHERE 子句的 SQL INNER JOIN 到 LINQ 格式

grails - 在Where查询中可以引用多少个关联级别是否有限制?