gpt4 book ai didi

php - Laravel 5 Eloquent : How to group relationship and get rank

转载 作者:搜寻专家 更新时间:2023-10-30 23:30:44 25 4
gpt4 key购买 nike

基本上我有一个点日志表如下:

user_id | points
1 | 10
2 | 20
1 | 30
1 | 4
2 | 6
6 | 8

我希望按总分对用户进行分组并显示他们的排名

这是我目前在我的 User.php 模型中的内容:

public function getPointRankAttribute() {
return $this->hasMany('App\PointLog')
->select(DB::raw('
SELECT s.*, @rank := @rank + 1 rank FROM (
SELECT user_id, sum(points) TotalPoints FROM t
GROUP BY user_id
) s, (SELECT @rank := 0) init
ORDER BY TotalPoints DESC
')
);
}

然后在我的blade模板中显示如下:

Your point rank: {{ $user->pointRank }}

最佳答案

不是很优雅,但它有效:

public function getPointRankAttribute() {
$ranks = DB::select('
SELECT s.*, @rank := @rank + 1 rank
FROM (
SELECT user_id, sum(points) TotalPoints
FROM pointLogs
GROUP BY user_id
) s, (SELECT @rank := 0) init
ORDER BY TotalPoints DESC
');
return collect($ranks)->where('user_id', $this->id)->first()->rank;
}

或者更优雅的解决方案:

public function getPointRankAttribute() {
$ranks = PointLog::query()
->select('user_id')->selectRaw('SUM(`points`) TotalPoints')
->groupBy('user_id')
->orderByDesc('TotalPoints')
->get();
return $ranks->search(function($pointLog) {
return $pointLog->user_id == $this->id;
}) + 1;
}

关于php - Laravel 5 Eloquent : How to group relationship and get rank,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49406787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com