首页 > 解决方案 > Laravel - 嵌套选择(雄辩)

问题描述

我有一个分数表,我必须按尝试编号分组,并获取我想使用 Eloquent 和 SQL 原始嵌套此查询的分数总和,并从尝试中获取最大分数并根据分数对其进行排序。我需要最终结果作为排行榜。

  $usersByScore =  Attempt::where('game_id',$id)
    ->select('user_id','attempt_no','game_id',DB::raw('SUM(score) as total_score'))
    ->groupBy('attempt_no')
    ->orderBy('total_score', 'DESC')
    ->get()

这给了我排行榜,但它有来自用户的所有尝试。我只需要按分数降序排列的每个用户的最大分数尝试。

标签: sqllaraveleloquent

解决方案


为此使用 distinct() 方法:我希望它会起作用。

$usersByScore =  Attempt::where('game_id',$id)
    ->select('user_id','attempt_no','game_id',DB::raw('SUM(score) as total_score'))
    ->groupBy('attempt_no')
    ->orderBy('total_score', 'DESC')
    ->distict()
    ->get()

推荐阅读