我正在尝试动态生成一个查询,该查询将允许以下列方式进行有条件的搜索
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语句?
答案 0 :(得分:3)
你应该试试这个:
$condition = ['or'];
foreach ($cols as $col) {
$condition[] = ['like', $col, $value];
}
$query->andFilterWhere($condition);