Answer the question
In order to leave comments, you need to log in
How to get top selling Laravel products?
Good afternoon.
$bestProductIds = Order::get()->map->products->flatten()->map->pivot->mapTogroups( function ($pivot) {
return [$pivot->product_id => $pivot->count];
})->map->sum()->sortDesc()->take(3)->keys()->toArray();
$bestProducts = Product::whereIn('id', $bestProductIds)->get();
Answer the question
In order to leave comments, you need to log in
Good afternoon, add sorting in the order you need.
$bestProductIds = Order::get()->map->products->flatten()->map->pivot->mapTogroups(function ($pivot) {
return [$pivot->product_id => $pivot->count];
})->map->sum()->sortDesc()->take(3)->keys()->toArray();
$bestProductIdsStr = implode(',', $bestProductIds);
$bestProducts = Product::whereIn('id', $bestProductIds)
->orderByRaw(DB::raw("FIELD(id, $bestProductIdsStr)"))
->get();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question