Ad

Laravel - Many-to-many Relation, Product Count By Product Feature

- 1 answer

Trying to get the count of products by its features(many-to-many) For instance,

Product::with([’features’])->where(category_id, $category_id)->get();

Product A->feature1->id

/feature2->id

/feature3->id

Product B->feature3->id

/feature4->id

/feature6->id

.....

how could i get product count from each feature (after filtered by product category)

I am not good at explain in wording, tried my best.

Final result feature 1 -> 19 products feature 2 -> 5 products ...

Ad

Answer

This will do the trick

   with(['products' => function($q) use($category_id){
                    $q->where('category_id',18);
                }])

                ->find($feature_ids)

                ->groupBy('feature_type_id');
Ad
source: stackoverflow.com
Ad