需要一种解决方案,根据获胜的最大积分(赢得的金额栏中的总和)列出用户。
用户和获胜两种模式。
用户有很多奖金。
$top_scorers = User::with('winnings')->orderBy("sum of amount column in all winnings")
答案 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();