1

I have a query in yii2:

$models = Company::find()->where('name like :q', ['q'=>/* Array here */])->all();

You can see that I have an array of q-elements I want to add to the query. How can I write the query so that it will check for one or many q elements (size of array unknown)?

2 Answers 2

5

If you realy need LIKE condition for your SQL statement instead of IN (look second answer):

$query = Company::find();
foreach($words as $word){
    $query->orWhere(['like','q', $word]);
}
$models = $query->all();

This will generate SQL staement like:

SELECT *
FROM table_name
WHERE field_name LIKE '%one%'
   OR field_name LIKE '%two%'
   OR field_name LIKE '%three%'
Sign up to request clarification or add additional context in comments.

1 Comment

This is a great solution I had never thought about.
3

As per the documentation at: http://www.yiiframework.com/doc-2.0/guide-db-active-record.html, the IN condition can be used to specify multiple possibilities using the something like the following pattern:

$models = Company::find()->where(['q'=>$qArray])->all();

This will generate an SQL statement like:

SELECT * FROM `company` WHERE q IN ('a','b'....);

assuming the contents of the $qArray variable is Array('a', 'b', ...)

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.