我有下表:
competitions (id, ...)
questions (id, ...)
teams (id, ...)
team_user (id, user_id, team_id, ...)
answer_user (user_id, competition_id, question_id, points, ...)
鉴于我们是根据团队用户积分的累积对列表进行排序,因此我试图构建一个查询以列出所有参加比赛ID = 20的团队。但是,有时有2个团队获得相同的总积分,因此我们需要在列表中首先显示能够达到该积分的团队,然后才是其他团队(基于created_at列的答案)
我可以使用以下查询获取此列表,但无法根据answer_user created_at列进行排序:
$ranks = Team::withCount(['answers' => function ($q) use ($competition_id) {
$q->where('competition_id', $competition_id)
->select(DB::raw('sum(points)'));
}])
->where('competition_id', $competition_id)
->orderBy('answers_count', 'desc')
->get();
编辑1 替换
时,我可以实现所需的排序->select(DB::raw('sum(points)')
使用
->select(DB::raw('max(answer_user.created_at)')
但是,我实际上希望两种聚合都能工作。基本上,找到每个团队得分的总分,然后根据时间对它们进行排序,首先得分是首先显示的得分。
答案 0 :(得分:0)
请在sortBy()
之后尝试使用sortByDesc()
或get()
函数
https://laravel.com/docs/5.8/collections#method-sortbydesc
$ranks = Team::withCount(['answers'=>function($q) use($competition_id){
$q->where('competition_id',$competition_id)->select(DB::raw('sum(points)'));
}])->where('competition_id',$competition_id)->get()->sortByDesc('answer_user');