You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何基于关联关系对相同course_id/section_id的duration列求和

enter image description here

场景1:统计指定course_id或指定section_id对应所有数据的总duration

直接用orWhere加sum方法即可:

// 替换YourModel为你实际的模型类名
$totalDuration = YourModel::where('course_id', $targetCourseId)
    ->orWhere('section_id', $targetSectionId)
    ->sum('duration');

场景2:分组聚合,统计每一组相同course_id/相同section_id的总duration

按course_id分组统计每个课程的总时长

$courseDurationList = YourModel::selectRaw('course_id, SUM(duration) as total_duration')
    ->groupBy('course_id')
    ->get();

返回结果中每条记录会包含course_id和对应总时长total_duration。

按section_id分组统计每个章节的总时长

$sectionDurationList = YourModel::selectRaw('section_id, SUM(duration) as total_duration')
    ->groupBy('section_id')
    ->get();

关联查询场景下的写法

如果你是从父模型关联查询子模型的duration总和,以Course模型关联Lesson模型(Lesson表包含course_id、section_id、duration字段)为例:

// Laravel 8及以上版本可以直接用withSum方法
// 统计每个课程下所有课时的总时长
$courses = Course::withSum('lessons as total_course_duration', 'duration')->get();

// 筛选出course_id为X或者关联的section_id为Y的所有课时总时长
$targetTotal = Course::where('id', $courseId)
    ->orWhereHas('sections', function ($query) use ($sectionId) {
        $query->where('id', $sectionId);
    })
    ->withSum('lessons', 'duration')
    ->get()
    ->sum('lessons_sum_duration');

注意事项

  • 使用groupBy时如果数据库开启了ONLY_FULL_GROUP_BY模式,select中出现的非聚合函数字段必须全部包含在groupBy的参数中,否则会抛出SQL错误。
  • 多表关联求和时注意避免关联数据重复导致求和结果偏大,必要时可以先对子查询结果去重再做求和计算。

内容的提问来源于stack exchange,提问作者Al Shahriar Mehedi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 20:36:03