laravel
描述:
数据表结构:
需求:
按照用户分组,并把该用户的所有unknown字段和important字段分别求和,最后按照该用户的sum(unknown)与sum(important)之和排序取前十。
代码:
代码语言:javascript复制 $lastYear = Carbon::today()->subYear();
$answers = Answer::whereIn('user_id', $classmateIdArr)
->where('start_time', '>', $lastYear)
->groupBy('user_id')
->selectRaw('user_id')
->selectRaw('sum(unknown) as unknownCount')
->selectRaw('sum(important) as importantCount')
->selectRaw('sum(important unknown) as allCount')
->having('allCount', '>', '0')
->orderBy('allCount', 'desc')
->distinct()
->take(10)->get();
return $answers;
希望对大家有启发,selectRaw可以写在一起,我习惯字段和逻辑分开。