vendredi 1 mars 2019

WhereHas not works as expected - Polymorphic many to many relation

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` = 'Action')

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire