Laravel 中某个字段出现次数最多的查询

Query that brings the most occurrences of a certain field in Laravel

我有以下查询:

$top_cont = DB::table('quests') 
       ->whereBetween('created_at', [Carbon::now()->startOfDay(), Carbon::now()->endOfDay()])  
       ->take(5)
       ->get(); 

quests table 有一个 user_id 列。我正在尝试获得贡献最多的前 5 user_id 人(即在这一天的任务 table 中拥有最多的行数)。

如何调整查询以带来出现次数最多的 user_id

如果有人可以原始 sql,这也会有帮助。

您可以使用以下查询:

    DB::table('quests') 
       ->whereBetween('created_at', [ Carbon::now()->startOfDay(),Carbon::now()->endOfDay()])
        ->select('user_id', DB::raw('count(*) as count') )
        ->groupBy('user_id')
        ->limit(5)
        ->orderBy ( 'count  DESC')
        ->get();

你可以这样做:

$top_cont = DB::table('quests') 
    ->select('user_id', DB::raw('count(*) as contributions'))
    ->whereDate('created_at', '>=', now()->startOfDay()) 
    ->take(5)
    ->groupBy('user_id')
    ->orderBy('contributions', 'desc')
    ->get(); 

这应该会为您提供 5 条记录,格式如下:

dd($top_cont);
=> Illuminate\Support\Collection {#3403
     all: [
       {#256
         user_id: 2,
         contributions: 51,
       },
       {#3417
         user_id: 975,
         contributions: 50,
       },
       {#3418
         user_id: 743,
         contributions: 46,
       },
       {#3419
         user_id: 538,
         contributions: 45,
       },
       {#3420
         user_id: 435,
         contributions: 18,
       },
     ],
   }