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

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 xcoln值。
目前我有一些类似的想法。
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为true时,将给出
SELECT * FROM model WHERE col1=val1 AND col2 LIKE '%val2%' AND col3 LIKE '%val2%';

或者当$condition1为false时,
SELECT * FROM model WHERE col2 LIKE '%val2%' AND col3 LIKE '%val2%';

当填充val2时,它的限制性太强,不会返回任何内容。
$query->orFilterWhere给出
SELECT * FROM model WHERE col1=val1 OR col2 LIKE '%val2%' OR col3 LIKE '%val2%';

$condition1 == true
SELECT * FROM model WHERE col2 LIKE '%val2%' OR col3 LIKE '%val2%';

!$condition1将返回时,它的权限太大,将返回不需要的结果。
如何遍历额外列的数组,并将它们作为val2子句附加到sql语句中?

最佳答案

你应该试试这个:

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

09-25 16:39