如何在 laravel 中获得排名

How to get rank in laravel

在我的 Laravel 5.3 应用程序中,投票 table 有一个净投票列。我想根据净票数找到视频的排名。我想显示如下列表的排名。我知道 sql @raw 方法。但是,我想使用 Laravel 方法。因为,还有其他一些table与该用户table联合,还需要做一些其他的做空。

视频table:

id     | net_votes| video_id | 
------ | -------: |:-------: |
1      |    5     |   1      |   
2      |    11    |   2      |   
3      |    3     |   1      |    
4      |    6     |   3      |    
5      |    5     |   2      |     

我想得到这样的结果

id     | net_votes| rank
------ | -------: |:----:
2      |    11    |   1
4      |    6     |   2
1      |    5     |   3
5      |    5     |   4
3      |    3     |   5

我现在正在使用这个代码。它的工作。但我想使用 Laravel Eloquent 方法。

$score_board_list = DB::select("SELECT *, total, @r:=@r+1 as rank,
           @l:=total FROM ( select username, first_name, video_title, 
           net_votes, sum(net_votes) as total from videos
           LEFT JOIN users ON videos.user_id = users.id
           LEFT JOIN profile ON users.id = profile.user_id
           group by videos.id order by total desc, videos.created_at desc ) totals, (SELECT @r:=0, @l:=NULL) rank");

这样做

将您的子查询存储到一个变量中

$subquery = "( 
     SELECT    username, 
               first_name, 
               video_title, 
               net_votes, 
               Sum(net_votes) AS total 
     FROM      videos 
     LEFT JOIN users 
     ON        videos.user_id = users.id 
     LEFT JOIN profile 
     ON        users.id = profile.user_id 
     GROUP BY  videos.id 
     ORDER BY  total DESC, 
               videos.created_at DESC ) totals";

然后相当于

Select * from (subquery)

变成Eloquent就是

DB::table(DB::raw('subquery'))

然后 select 自定义列

// for example  
->select(DB::raw('@r:=@r+1 as rank'))

所以您的查询构建器会像这样

$subquery = "( 
     SELECT    username, 
               first_name, 
               video_title, 
               net_votes, 
               Sum(net_votes) AS total 
     FROM      videos 
     LEFT JOIN users 
     ON        videos.user_id = users.id 
     LEFT JOIN profile 
     ON        users.id = profile.user_id 
     GROUP BY  videos.id 
     ORDER BY  total DESC, 
               videos.created_at DESC ) totals";


$score_board_list = DB::table(DB::raw($subquery))
->select(
    '*', 
    'total', 
    DB::raw('@r:=@r+1 as rank'), 
    DB::raw('@l:=total'))
->get();