在 CakePHP 3.4x 中,AND 条件后跟 BETWEEN 之间的 OR
AND condition followed by OR between BETWEEN in CakePHP 3.4x
我想得到什么:
SELECT col,col,col FROM x WHERE id = :c0 AND ((colx BETWEEN :c1 AND :c2) OR (colx BETWEEN :c3 AND :c4))
我试过的:
$finalList = $finalList->find()->where(['id' => $id]);
foreach($dataArray as $y):
$finalList = $finalList->orWhere(function($expressions) use ($y['min'], $y['max']) {
return $expressions->between('colx', $y['min'], $y['max']);
}
endforeach;
我得到的是:
SELECT col,col,col FROM x WHERE id = :c0 OR colx BETWEEN :c1 AND :c2 OR colx BETWEEN :c3 AND :c4
我希望 id 需要 并且 OR 介于 BETWEEN
之间
这就是 orWhere()
的工作原理。引自 API 文档:
It is important to notice that when calling this function, any previous set
of conditions defined for this query will be treated as a single argument for
the OR operator. This function will not only operate the most recently defined
condition, but all the conditions as a whole.
虽然它并不过分直截了当,这就是 orWhere()
has recently been deprecated.
的原因
要使用 orWhere()
实现此功能,您必须在 orWhere()
之后应用 where()
(或 andWhere()
),即:
$finalList = $finalList->find();
foreach($dataArray as $y) {
// ... apply orWhere()
}
$finalList->where(['id' => $id]);
或者一直使用表达式生成器:
$finalList = $finalList->where(function ($exp) use ($dataArray) {
$or = $exp->or_([]);
foreach($dataArray as $y) {
$or->between('colx', $y['min'], $y['max']);
}
return $exp->add(['id' => 1, $or]);
});
另见
我想得到什么:
SELECT col,col,col FROM x WHERE id = :c0 AND ((colx BETWEEN :c1 AND :c2) OR (colx BETWEEN :c3 AND :c4))
我试过的:
$finalList = $finalList->find()->where(['id' => $id]);
foreach($dataArray as $y):
$finalList = $finalList->orWhere(function($expressions) use ($y['min'], $y['max']) {
return $expressions->between('colx', $y['min'], $y['max']);
}
endforeach;
我得到的是:
SELECT col,col,col FROM x WHERE id = :c0 OR colx BETWEEN :c1 AND :c2 OR colx BETWEEN :c3 AND :c4
我希望 id 需要 并且 OR 介于 BETWEEN
之间这就是 orWhere()
的工作原理。引自 API 文档:
It is important to notice that when calling this function, any previous set of conditions defined for this query will be treated as a single argument for the OR operator. This function will not only operate the most recently defined condition, but all the conditions as a whole.
虽然它并不过分直截了当,这就是 orWhere()
has recently been deprecated.
要使用 orWhere()
实现此功能,您必须在 orWhere()
之后应用 where()
(或 andWhere()
),即:
$finalList = $finalList->find();
foreach($dataArray as $y) {
// ... apply orWhere()
}
$finalList->where(['id' => $id]);
或者一直使用表达式生成器:
$finalList = $finalList->where(function ($exp) use ($dataArray) {
$or = $exp->or_([]);
foreach($dataArray as $y) {
$or->between('colx', $y['min'], $y['max']);
}
return $exp->add(['id' => 1, $or]);
});
另见