php - Laravel using groupBy and unique -


i using laravel , have music table, order_items table , users table. music items have user , user can have multiple music items. trying top 100 selling music, want return 1 music item per user (the top selling 1 of music sales).

my code is:

$items = db::table('order_items') ->join('music', 'music.id', '=', 'order_items.music_id) ->groupby('music_id') ->select('order_items.user_id', 'order_items.music_id', db::raw('count(*) sold')) ->orderby(db::raw('sold_count'), 'desc');  $items = collect($items)->unique('user_id')->values()->take(100); 

this seem return data need, first query returns more 35k records takes while run. can place limit on initial query can not guarantee there 100 items once grouped user.

is there better way this? can run in 1 query?


Comments