keeg
keeg

Reputation: 3978

search for multiple keywords in the same field in Yii2

I need to search several key words that appear in the same database field. For example if field contains "The quick brown fox jumps over the lazy dog" and someone searches for "quick" and "dog" this should be returned as a match.

so I take the search field and explode it into an array based on spaces:

$terms = explode( " ", $this->search_term );

Then I thought I'd throw this into a loop:

foreach ($terms as $key) {
    $query->andFilterWhere( [
        'or',
        [ 'like', 'item.name', $key ],
    ] );
}

However this isn't working, plus it's not very elegant.

Upvotes: 0

Views: 1050

Answers (2)

soju
soju

Reputation: 25312

You should simply build properly the condition parameter, e.g. :

$condition = ['or'];
foreach ($terms as $key) {
    $condition[] = ['like', 'item.name', $key];
}
$query->andWhere($condition);

Upvotes: 3

Mohan Rex
Mohan Rex

Reputation: 1674

I think you have to join the conditions by using or conditions.

foreach ($terms as $key) {
    $query->orFilterWhere( [
        'or',
        [ 'like', 'item.name', $key ],
    ] );
}

This is how you have to add another or conditions. See here for further details. I guess there is no other ways to do this without doing for loop.

Upvotes: 2

Related Questions