Reputation: 21
I have 1 table postad with fields (title,cat1,cat2,cat3,cat4,location,city,area)
Now I am passing 2 values category_id and location searching results from post ad table .
Here is my code // Search for category,location
public function scopeLocationSearch($query,$post_location,$category_id)
{
return $query->category($category_id)->location($post_location)->get();
}
category and location scopes are Scopes are as follows:
public function scopeCategory($query,$cat_id)
{
return $query->where('cat1', $cat_id)
->orWhere('cat2', $cat_id)
->orWhere('cat3', $cat_id)
->orWhere('cat4', $cat_id);
}
public function scopeLocation($query,$location)
{
return $query->where('location','LIKE','%'.$location.'%')
->orWhere('city','LIKE', '%'.$location.'%')
->orWhere('area','LIKE', '%'.$location.'%');
}
Individually these scopes are giving results what I want but when I am calling locationsearch , it giving wrong results. It is just providing me OR
results but I want AND
results.
Thanks
Upvotes: 2
Views: 723
Reputation: 111829
When you use or
operator for conditions, you should wrap whole condition into closure to make sure valid query will be executed.
Your methods should look like so:
public function scopeCategory($query,$cat_id)
{
return $query->where(function($query) use ($cat_id) {
$query->where('cat1', $cat_id)
->orWhere('cat2', $cat_id)
->orWhere('cat3', $cat_id)
->orWhere('cat4', $cat_id);
});
}
public function scopeLocation($query,$location)
{
return $query->where(function($query) use ($location) {
$query->where('location','LIKE','%'.$location.'%')
->orWhere('city','LIKE', '%'.$location.'%')
->orWhere('area','LIKE', '%'.$location.'%');
});
}
Upvotes: 1