php - 在 CakePHP 3 中,andWhere()、orWhere()、where() 方法的计算顺序是什么?

标签 php mysql sql cakephp

我对我在 CakePHP 3 文档查询生成器的高级条件中读到的内容感到困惑:https://book.cakephp.org/3.0/en/orm/query-builder.html#advanced-conditions

它给出了以下代码

$query = $articles->find()
->where(['author_id' => 2])
->orWhere(['author_id' => 3])
->andWhere([
    'published' => true,
    'view_count >' => 10
])
->orWhere(['promoted' => true]);

并说这等同于此 SQL:

SELECT *
FROM articles
WHERE (promoted = true
OR (
  (published = true AND view_count > 10)
  AND (author_id = 2 OR author_id = 3)
))

我根本不理解它是如何工作的,因为 PHP 中的条件顺序与生成的 SQL 语句中的顺序不同(例如 ->orWhere(['promoted' => true]) 在 PHP 中位于最后,但在 SQL 语句中位于第一。为什么?)。

文档中唯一可能相关的信息是:

Each method sets the combining operator used between the current and previous condition.

这是文档中的错误,还是有人可以用更好的方式解释这到底是如何工作的?

虽然我意识到这几乎肯定是错误的,但我对该 SQL 的计算方式的理解是:

SELECT *
FROM articles
WHERE (author_id = 2 OR author_id = 3)
AND ( (published = true AND view_count > 10) OR promoted = true)

最佳答案

当您使用 orWhere 查询构建器时,它会采用整个 where 子句并将其放在 OR 运算符的一侧,这就是为什么它是这样的

WHERE (
   promoted = true
   OR 
   (
      (published = true AND view_count > 10)
      AND 
      (author_id = 2 OR author_id = 3)
   )
)

你必须这样写才能得到想要的输出

    $query = $this->Orders->find()
        ->where(['author_id' => 2])
        ->orWhere(['author_id' => 3])
        ->andWhere([
            'OR'=>[
                ['promoted' => true],
                ['published' => true,
                    'view_count >' => 10]
            ]
        ]);

     $query = $this->Orders->find()
            ->where(['author_id' => 2])
            ->orWhere(['author_id' => 3])
            ->andWhere(function (QueryExpression $exp) {
                return $exp->or_([
                    'promoted' => true,
                    ['published' => true,
                        'view_count >' => 10]
                ]);
            })->toArray();

关于php - 在 CakePHP 3 中,andWhere()、orWhere()、where() 方法的计算顺序是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43656590/

相关文章:

php - 如何使用更新语句更新数据库值?

php - MySQL启动错误-端口已被使用

java - 管理存储在mysql数据库中的用户的权限

c# - 我的 SQL 插入格式有什么问题,c# 没有执行它?

sql - Oracle to_date 季度格式函数

php - 在 Laravel 中翻译为特定语言

php过期日期红绿灯系统

MySQL:将每组中的前 N ​​行插入到表中。假设有数百万组

sql - 用另一个表中的值替换 id

php - 公共(public),私有(private)和 protected 之间有什么区别?