【问题标题】:How to get rank in laravel如何在laravel中获得排名
【发布时间】:2016-12-21 01:24:17
【问题描述】:

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

视频表:

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 Method。

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

【问题讨论】:

  • 根据净投票的用户排名 --> 你可以按 净投票 降序排列它们,你得到了第一名,第二名等..好吧,至少,给了我们一个你尝试过的例子..还有**加入这个用户表**很有趣,如果你认为它很重要,也发布它..详细为可能
  • @BagusTesa 我已经编辑了我的问题。谢谢。
  • 你的意思是你想使用 laravel 查询生成器?
  • 是的。 @NewbeeDev
  • 你应该研究一下 MVC 和 Eloquent。拥有 Laravel 5.3 并进行这样的原始查询毫无意义......

标签: laravel eloquent laravel-5.3


【解决方案1】:

这样做

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

$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'))

然后选择自定义列

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

【讨论】:

    猜你喜欢
    • 2021-01-18
    • 2015-05-16
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    • 2016-04-10
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多