Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel 5雄辩:如何分组关系并获得排名_Php_Mysql_Database_Laravel_Eloquent - Fatal编程技术网

Php Laravel 5雄辩:如何分组关系并获得排名

Php Laravel 5雄辩:如何分组关系并获得排名,php,mysql,database,laravel,eloquent,Php,Mysql,Database,Laravel,Eloquent,基本上,我有一个点日志表,如下所示: user_id | points 1 | 10 2 | 20 1 | 30 1 | 4 2 | 6 6 | 8 Your point rank: {{ $user->pointRank }} 我希望根据用户的总分对他们进行分组,并显示他们的排名 这是迄今为止我在User.php模型中的内容: public function getPointRankAttribute() {

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

user_id | points
1       | 10
2       | 20
1       | 30
1       | 4
2       | 6
6       | 8
Your point rank: {{ $user->pointRank }}
我希望根据用户的总分对他们进行分组,并显示他们的排名

这是迄今为止我在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
        ')
    );
}
然后显示在我的刀片模板中,如下所示:

user_id | points
1       | 10
2       | 20
1       | 30
1       | 4
2       | 6
6       | 8
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;
}

你能分享你的模型吗?你能把答案标记为接受吗?这会向其他用户显示问题已解决。