Laravel多对多关联(belongsToMany)获取内容计数报错解决
问题:Laravel多对多关联中获取关联内容总数报错
我在项目里定义了两个多对多关联的模型:
Contents模型
class Contents extends Model { protected $table = 'contents'; protected $guarded = ['id']; public function categories() { return $this->belongsToMany(ContentCategories::class); } }
ContentCategories模型
class ContentCategories extends Model { protected $table = 'contents_categories'; protected $guarded = ['id']; public function contents() { return $this->belongsToMany(Contents::class); } }
项目要求每个内容必须关联一个或多个分类,我尝试用下面的代码获取关联到分类的内容总数:
$categories = ContentCategories::with('contents'); dd($categories->contents->count());
结果抛出了错误:
"Undefined property: Illuminate\Database\Eloquent\Builder::$contents"
解决方案
嘿,这个问题其实很常见,我来帮你理清楚问题出在哪以及怎么解决:
错误原因
你写的$categories = ContentCategories::with('contents');返回的是Eloquent查询构建器对象,而不是实际的分类模型实例集合。构建器只是用来准备查询的,还没执行数据库查询,所以它根本没有contents这个属性,自然会报错啦。
不同需求的解决方法
根据你的实际需求,有几种不同的处理方式:
1. 获取每个分类对应的内容数量
如果你想拿到所有分类,同时知道每个分类下关联了多少内容,用Laravel提供的withCount方法最方便:
// 加载分类并统计每个分类的内容数 $categories = ContentCategories::withCount('contents')->get(); // 遍历分类就能拿到每个分类的内容数量 foreach ($categories as $category) { echo "分类{$category->id}的内容数:{$category->contents_count}"; }
withCount会自动在查询中加入统计子句,返回的每个分类模型会多出一个contents_count属性,直接用就行,效率也很高。
2. 获取所有关联了分类的内容总数量(去重后)
如果你的需求是统计所有至少关联了一个分类的内容总数(不管属于哪个分类,一个内容关联多个分类也只算一次),可以这样写:
$totalRelatedContents = Contents::whereHas('categories')->distinct()->count();
whereHas用来筛选出有分类关联的内容,distinct避免重复统计,最后count()得到总数。
3. 获取单个分类下的内容数量
要是你只想查某个特定分类的内容数,先拿到该分类的模型实例再统计:
// 先找到目标分类 $category = ContentCategories::find($yourCategoryId); // 统计该分类下的内容数 $contentCount = $category->contents->count();
这里find()会执行查询并返回模型实例,之后访问contents会加载关联的内容集合,再用count()就能得到数量。
内容的提问来源于stack exchange,提问作者DolDurma
相关产品推荐
相关产品推荐

