Home > Enterprise >  Can't get the right results using the orWhere query in Yii2 framework
Can't get the right results using the orWhere query in Yii2 framework

Time:01-03

I am using the following code in Yii2 framework to get all the results (cars in my case) from mySQL database that contains specific tags:

$query->orWhere(['and',
            ['car_extra.field_id' => $this->carField->id],
            ['like', 'car_extra.value', $searchValue]
        ]); 

For example there are 2 cars in the database.

Car Ford contains the tags: abs, dvd-player

Car Jeep contains the tag: Parktronic

When i search for the tag "abs" the search displays the Ford car which is ok, but when i search for both "abs" and "Parktronic" at the frontend search form, the search returns zero results because it search in the database for a single car that contain both of the tags "abs" and "Parktronic". How can i modify my code above so i can get as result both cars: Ford and Jeep ?

CodePudding user response:

I have been using yii2 for 5 months but query building is really tough job. But here is the solution you can use this.

$query->andWhere(['car_extra.field_id' => $this->carField->id]);

$searchValue=explode(' ',$searchValue);
foreach($searchValue as $searchParam)
{
    $query->orWhere(['like', 'car_extra.value', $searchParam]); 
}

I have broken your search parameter into array and using it as single search value. If you your search query is not separated with space then you can use explode(',',$searchValue) anything.

CodePudding user response:

You culd use a IN clause based on ana array for the searched values

  $myArray = ["abs","Parktronic"]
  $query->where(['in','car_extra.value', $myArray]); 
  • Related