【问题标题】:Laravel - Nested select (Eloquent)Laravel - 嵌套选择(雄辩)
【发布时间】:2020-02-25 04:54:04
【问题描述】:

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

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

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

【问题讨论】:

  • 您是否尝试使用orderByRaw。可以是->orderByRaw('SUM(score) DESC')

标签: sql laravel eloquent


【解决方案1】:

为此使用 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()

【讨论】:

    【解决方案2】:

    得到解决方案 - 实现了 from 方法来嵌套查询

    $usersByScore =  Attempt::with('user')
            ->select(DB::raw('MAX(tscore) as total_score, user_id,attempt_no'))
            ->from(DB::raw('(SELECT user_id,attempt_no,SUM(score) as tscore FROM 
             attempts WHERE game_id = '.$id.' GROUP By attempt_no,user_id) AS T'))
            ->groupBy('user_id')
            ->get();
    

    【讨论】:

      猜你喜欢
      • 2015-06-22
      • 1970-01-01
      • 2020-07-29
      • 1970-01-01
      • 2018-06-27
      • 1970-01-01
      • 2021-05-22
      • 2014-06-02
      • 2020-05-10
      相关资源
      最近更新 更多