Yii2 - 使用AND +多个OR生成ActiveRecord查询

时间:2015-09-23 11:46:36

标签: php activerecord yii2

我正在尝试动态生成一个查询,该查询将允许以下列方式进行有条件的搜索

SELECT * FROM model WHERE col1=val1 AND (col2 LIKE '%val2%' OR col3 LIKE '%val2%');

SELECT * FROM model WHERE col2 LIKE '%val2%' OR col3 LIKE '%val2%';

取决于初始条件以及数组中有n x coln个值。

目前我有这些方面的东西。

if ($condition1) {
   $query = Model::find()->where(['col1' => $val]);
} else {
   $query = Model::find();
}

foreach ($cols as $col) {
   $query->andFilterWhere(['or',['like', $col, $value]]);
}

$dataProvider = new ActiveDataProvider(['query' => $query]);

但是,当$condition1为真时,它会提供

的基础查询结构
SELECT * FROM model WHERE col1=val1 AND col2 LIKE '%val2%' AND col3 LIKE '%val2%';

$condition1为假时

SELECT * FROM model WHERE col2 LIKE '%val2%' AND col3 LIKE '%val2%';

当填充val2时限制性太强,不会返回任何内容。

并在$query->orFilterWhere提供

的基础结构时使用$condition1 == true
SELECT * FROM model WHERE col1=val1 OR col2 LIKE '%val2%' OR col3 LIKE '%val2%'; 

!$condition1

SELECT * FROM model WHERE col2 LIKE '%val2%' OR col3 LIKE '%val2%'; 

val2返回时过于宽松并且会返回不需要的结果。

如何迭代额外列的数组并将它们作为coln LIKE $value子句附加到SQL语句?

1 个答案:

答案 0 :(得分:3)

你应该试试这个:

$condition = ['or'];
foreach ($cols as $col) {
    $condition[] = ['like', $col, $value];
}
$query->andFilterWhere($condition);