Laravel雄辩的顺序由相关模型的列总和(有许多关系)

时间:2019-03-15 09:20:45

标签: php laravel eloquent

需要一种解决方案,根据获胜的最大积分(赢得的金额栏中的总和)列出用户。
用户和获胜两种模式。 用户有很多奖金。

 $top_scorers = User::with('winnings')->orderBy("sum of amount column in all winnings")

2 个答案:

答案 0 :(得分:1)

反之亦然,这会更容易:

 $usersByWinnings = Winning::with('user')
       ->select('user_id', \DB::raw('SUM(amount) as winnings'))
       ->groupBy('user_id')
       ->orderBy('winnings', 'DESC')
       ->get()->map(function (Winning $winning) {
             return $winning->user;
        });

或者,您可以进行后处理sortBy

$top_scorers = User::with('winnings')->get()
                  ->sortByDesc(function (User $user) {
                       return $user->winnings->sum('amount');
                   });

答案 1 :(得分:1)

您可以使用修改后的withCount()

$top_scorers = User::withCount(['winnings as amount' => function ($query) {
    $query->select(DB::raw('sum(amount)'));
}])->orderByDesc('amount')->get();