1

我想得到什么:

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 之间

4

1 回答 1

2

就是这样orWhere()工作的。引用 API 文档:

需要注意的是,在调用此函数时,之前为此查询定义的任何一组条件都将被视为 OR 运算符的单个参数。此函数不仅会操作最近定义的条件,还会操作整个条件。

不过,这并不太直接,这就是orWhere()最近被弃用的原因。

要使用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]);
});

也可以看看

于 2017-07-24T15:03:33.657 回答