我对我在 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/