laravel ORM分组求和(多个字段),并按结果再次求和并排序

2023-09-05 15:59:46 浏览数 (4)

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可以写在一起,我习惯字段和逻辑分开。

0 人点赞