简体   繁体   English

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

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

I have the following query:我有以下查询:

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

The quests table has a user_id column. quests表有一个user_id列。 I'm trying to get the top 5 user_id s who have the most contributions (ie has the most number of rows in the quests table for this day).我试图获得贡献最多的前 5 个user_id (即今天在 quests 表中的行数最多)。

How can I adjust the query to bring the user_id s that have the most occurrences?如何调整查询以获取出现次数最多的user_id

If someone can do it in raw sql, this will be helpful too.如果有人可以在原始 sql 中做到这一点,这也会有所帮助。

You could do something like this:你可以这样做:

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

This should give you 5 records with this form:这应该为您提供 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, }, ], }

You can use following query:您可以使用以下查询:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM