AND条件,然后是CakePHP 3.4x中BETWEEN之间的OR

时间:2017-07-24 14:14:06

标签: cakephp cakephp-3.4

我想要的是什么:

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 必需和BETWEEN之间的OR

1 个答案:

答案 0 :(得分:2)

orWhere()的工作原理。引用API文档:

  

重要的是要注意,在调用此函数时,任何先前的集合   为此查询定义的条件将被视为单个参数   OR运算符。此功能不仅会运行最近定义的功能   条件,但所有条件作为一个整体。

虽然不过于直截了当,这就是为什么orWhere() has recently been deprecated

要使用orWhere()启用此功能,您必须在where()之后应用andWhere()(或orWhere()),即:

$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]);
});

另见