Yii2 ActiveQuery 'OR LIKE' filter
Asked Answered
M

1

25

I have a task - add to the search model searching by full name. Full name is first name + last name. So I need to build query like

WHERE first_name LIKE '%var%' OR last_name LIKE '%var%'

The only way I could do it :

$query->andFilterWhere([
    'OR',
    'profiles.first_name LIKE "%' . $this->userFullName . '%" ',
    'profiles.last_name LIKE "%' . $this->userFullName . '%"'
]);

But I don't like it because % it's unsafe. I don't know how... I think there is a way to build a such query with Yii2 active builder, and I would like to get in results smth like

$query->andFilterWhere(['LIKE', 'profiles.first_name', $this->userFullName]);
$query->andFilterWhere(['OR LIKE', 'profiles.last_name', $this->userFullName]);

The problem is in the query Like, I could use array as the values that attribute will be compared but I can't use array as list of attributes to be compared with.

or

$subQuery1 = Profile::find()->Where(['LIKE', 'profiles.first_name', $this->userFullName]);
$subQuery2 = Profile::find()->Where(['LIKE', 'profiles.last_name', $this->userFullName]);
// I think its overloaded(3 queries instead of 1 but still) and the final query
$query->andFilterWhere([
    'OR',
    $subQuery1,
    $subQuery2
]);

Any ideas on how to build a query without "%"?

Manet answered 18/2, 2015 at 20:0 Comment(0)
A
56

You should simply try :

$query->andFilterWhere([
    'or',
    ['like', 'profiles.first_name', $this->userFullName],
    ['like', 'profiles.last_name', $this->userFullName],
]);

or: similar to the and operator except that the operands are concatenated using OR. For example, ['or', ['type' => [7, 8, 9]], ['id' => [1, 2, 3]] will generate (type IN (7, 8, 9) OR (id IN (1, 2, 3))).

Read more : http://www.yiiframework.com/doc-2.0/yii-db-queryinterface.html#where()-detail

Aw answered 18/2, 2015 at 21:9 Comment(2)
is it works? I cant check because already left the work, but if its works thx a lot. :)Manet
how to find comma seprated values using FIND_IN_SET?Chickenhearted

© 2022 - 2024 — McMap. All rights reserved.