Laravel 9.x中通过HasManyThrough获取Content_hashtag计数
实现Laravel 9.x中关联标签的统计字段
方法一:利用withCount关联统计
这种方法需要先在Hashtag模型中定义与Content_hashtag的关联,再在Chapter的hasManyThrough关联中加载统计字段:
- 在
Hashtag模型中添加关联:
// app/Models/Hashtag.php public function contentHashtags() { return $this->hasMany(Content_hashtag::class, 'hashtag_id'); }
- 修改
Chapter模型中的hashtags关联,加入withCount:
// app/Models/Chapter.php public function hashtags() { // 请根据你的实际表结构调整hasManyThrough的参数 return $this->hasManyThrough( Hashtag::class, Section::class, // 中间关联模型,若你的路径是Chapter->Section->Content_hashtag->Hashtag,需替换为Content_hashtag 'chapter_id', // 中间表关联Chapter的外键 'id', // Hashtag表的主键 'id', // Chapter表的主键 'id' // 中间表关联后续模型的外键 )->withCount(['contentHashtags as content_hashtag_count']); }
方法二:手动selectRaw+分组统计
若不想在Hashtag模型中额外定义关联,可直接通过联表和分组实现统计:
// app/Models/Chapter.php public function hashtags() { return $this->hasManyThrough(Hashtag::class, Section::class) ->selectRaw('hashtags.*, COUNT(content_hashtag.id) as content_hashtag_count') ->leftJoin('content_hashtag', 'content_hashtag.hashtag_id', '=', 'hashtags.id') ->groupBy('hashtags.id'); }
注意:用
leftJoin可保留无对应Content_hashtag记录的标签,统计值为0;若用join会过滤掉这类标签。若数据库开启严格模式,需确保groupBy包含所有非聚合字段,可在config/database.php中调整strict参数为false,或显式分组所有选中字段。
使用方式
获取Chapter数据时预加载关联标签,即可直接访问统计字段:
$chapter = Chapter::with('hashtags')->find($chapterId); // 遍历标签并查看统计值 foreach ($chapter->hashtags as $hashtag) { echo "标签:{$hashtag->name},关联内容数:{$hashtag->content_hashtag_count}"; }
内容的提问来源于stack exchange,提问作者dvb42a
相关产品推荐
相关产品推荐

