在我的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");
答案 0 :(得分: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();