Search code examples
laraveleloquentsummax

Laravel query - get the best selling item


I'm new to Laravel and I use Laravel 5.1.

I have this table in database: enter image description here

This is table for purchased itesm. I want to know what is the best way to calculate the best selling voucher - every purchase has voucher_id ...


Solution

  • The best way of doing it is using one single query for counting and also getting the id of the best seller in the same query:

    PurchasedItem::select(DB::raw('COUNT(id) as cnt', 'voucher_id'))->groupBy('voucher_id')->orderBy('cnt', 'DESC')->first();