V
V
Vladislav2020-08-19 16:28:06
Laravel
Vladislav, 2020-08-19 16:28:06

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();


$bestProductIds contains product IDs from largest to smallest, that is, the first ID is where there are more sales.
Outputs 4, 5, 1

But when selecting $bestProducts using the whereIn method, they are displayed not in the same order, but in chronological order, 1, 4, 5

How to get them in the order that lies in the $bestProductIds array?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2020-08-19
@Vladddosss

Will it fit? https://coderoad.ru/38574669/Laravel-%D1%81%D0%BE%...

A
Anton October, 2020-08-19
@Lyrium

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 question

Ask a Question

731 491 924 answers to any question