我正在尝试动态生成一个查询,该查询将允许按以下方式有条件地进行搜索
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
为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);