hsntngr
9 months ago

WhereHas method doesn't work as expected

Posted 9 months ago by hsntngr

I'm trying to build a filter query but when I filter using whereHas method it returns extremely odd results.

when($request->has("brand", function($q) use ($request) {
   $q->whereHas("tags", function ($q) use ($request) {
        $q->where("tags.id", $request->brand); # brand id
   });
}))

Here is sql result if I filter only by brand (by tag)

 "select `products`.`id`, `products`.`title`, `products`.`slug`, `products`.`price` from `products` 
where exists (select * from `tags` inner join `taggables` on `tags`.`id` = `taggables`.`tag_id` 
where `products`.`id` = `taggables`.`taggable_id` 
and `taggables`.`taggable_type` = 'App\Models\Product' and `tags`.`id` = '10')";

It returns couple result but doesn't relevant with above query. Results even have not same brand.

But when I send brand name instead id and change query like $q->where("tags.name", $request->brand); # brand name, it working as well

select `products`.`id`, `products`.`title`, `products`.`slug`, `products`.`price` from `products` 
where exists (select * from `tags` inner join `taggables` on `tags`.`id` = `taggables`.`tag_id` 
where `products`.`id` = `taggables`.`taggable_id` 
and `taggables`.`taggable_type` = 'App\Models\Product' and `tags`.`name` = 'Phone')

What is wrong with it ? I'm using polyhmorphic many yo many relationship between product and tags, there some other taggable models..

Please sign in or create an account to participate in this conversation.