Laravel嵌套关联查询中为LessonFiles添加访问统计计数
解决方案:给嵌套关联的LessonFiles添加访问次数统计
没问题,我来帮你搞定这个需求!你想要给每个嵌套在Lessons里的LessonFiles记录加上对应的访问次数统计,Laravel提供了几种优雅的实现方式,下面给你两种常用方案:
方案一:通过定义关联+withCount实现(推荐,复用性强)
首先在LessonFiles模型里定义一个和LessonsView的关联关系,这样后续任何地方需要统计访问量都能直接复用:
// app/Models/LessonFiles.php class LessonFiles extends Model { // 你的其他代码... public function views() { // 这里要确保LessonsView的lesson_file_key字段对应LessonFiles的lesson_file_key字段 return $this->hasMany(LessonsView::class, 'lesson_file_key', 'lesson_file_key'); } }
然后修改你原有的查询代码,在加载files关联的时候加上withCount('views'),这样每个LessonFiles实例会自动带上views_count属性,就是对应的访问次数:
$months = Month::with(['lessons' => function ($query) { $query->with(['files' => function ($fileQuery) { $fileQuery->withCount('views'); }]); }])->get();
之后你就可以这样访问访问次数:
foreach ($months as $month) { foreach ($month->lessons as $lesson) { foreach ($lesson->files as $file) { echo "文件{$file->id}的访问次数:{$file->views_count}"; } } }
方案二:通过子查询直接统计(无需额外定义关联)
如果只是临时需求,不想给LessonFiles加新关联,可以直接在查询里用selectSub添加子查询统计:
$months = Month::with(['lessons' => function ($query) { $query->with(['files' => function ($fileQuery) { $fileQuery->select('*') ->selectSub(function ($subQuery) { $subQuery->from('lessons_views') ->whereColumn('lessons_views.lesson_file_key', 'lesson_files.lesson_file_key') ->selectRaw('count(*)'); }, 'view_count'); }]); }])->get();
这种方式下,每个LessonFiles实例会有view_count属性,用法和方案一一致。
注意事项
- 确保
lessons_views表中的lesson_file_key字段和lesson_files表中的对应字段名称匹配,如果不一样要调整whereColumn里的参数。 - 方案一的优势是关联可以复用,后续任何需要统计LessonFiles访问量的地方都能直接用
withCount('views'),更符合Laravel的Eloquent设计思想。
内容的提问来源于stack exchange,提问作者DolDurma
相关产品推荐
相关产品推荐

