Laravel 查询生成器 - return 组合条目的最大值

Laravel Query Builder - return the max value of combined entries

使用 Laravel 的查询构建器,我试图获得特定游戏的最高综合分数。

我目前有下面的方法可以找到游戏的单个最高分。

public function getHighestScore()
{
    return DB::table('scores')
        ->join('games', 'scores.game_id', '=', 'games.id')
        ->join('users', 'scores.user_id', '=', 'users.id')
        ->select('scores.score as return')
        ->where('scores.game_id', $this->id)
        ->get()->max('return');
}

所以打电话

$game = Game::find(5);
$game->getHighestScore();

正确输出

784

但是现在我需要能够获得游戏的最高(综合用户分数)并通过 id 获得该用户。 如果可能的话,我真的很想通过一个查询来实现这一目标?

我的分数table如下所示:

+---------+----------+----------+--------+
| id      | game_id  | user_id  | score  |
+---------+----------+----------+--------+
| 97      |        5 |        3 |    234 |
| 123     |        3 |        3 |    102 |
| 300     |        5 |        1 |     99 |
| 422     |        5 |        1 |    784 |
| 531     |        5 |        3 |    221 |
| 612     |        3 |        3 |    222 |
| 798     |        3 |        3 |    379 |
+---------+----------+----------+--------+

所以像这样:

$game = Game::find(5);
$game->getUserWithHighestCombinedScore();

这可能吗? 我的查询必须包括什么?

为了帮助澄清,我已经包含了以下内容。

如果您将 user_id 的每场比赛得分结合起来,假设的 table 将如下所示:

+---------+----------+----------+-----------------+
| id      | game_id  | user_id  | combined_score  |
+---------+----------+----------+-----------------+
|         |        5 |        3 |             455 | 
|         |        5 |        1 |             883 |  
|         |        3 |        3 |             703 |  
+---------+----------+----------+-----------------+

并称其为

$game->getUserWithHighestCombinedScore();

return 两者都会

// user_id
1
// combined_score of
883

所以它们需要在 ->select() 属性中。

这可能吗?

所以首先,对于你的第一个查询,我认为你不需要那么多joins你可以简单地这样做。

return DB::table('scores')->where('game_id', $this->id)->max('score');

然后对于你的问题,我认为这应该可行。

    return DB::table('scores')
        ->where('game_id', $this->id)
        ->select('user_id', DB::raw('SUM(score) as total'))
        ->groupBy('user_id')
        ->orderByDesc('Total')
        ->take(1)
        ->get();