3

I am trying to dynamically generate a query which will allow searching conditionally in the following manner

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

or

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

depending on an initial condition and where there are n x coln values in an array.

At the moment I have something along these lines.

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]);

but, when $condition1 is true, that gives an underlying query structure of

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

or when $condition1 is false,

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

which when val2 is populated is too restrictive and wont return anything.

and using $query->orFilterWherewhen $condition1 == true gives an underlying structure of

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

or when !$condition1

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

which when val2 will return is too permissive and will return results that aren't desired.

How can I iterate over the array of extra columns and append them as coln LIKE $value clauses to the SQL statement?

1 Answer 1

3

You should simply try this :

$condition = ['or'];
foreach ($cols as $col) {
    $condition[] = ['like', $col, $value];
}
$query->andFilterWhere($condition);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.