[英]Laravel get count on belongsToMany relationship
在我的项目中,我有两种模型:
内容:
class Contents extends Model
{
protected $table = 'contents';
protected $guarded = ['id'];
public function categories()
{
return $this->belongsToMany(ContentCategories::class);
}
}
和类别:
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
变量是一个集合,其中每个类别都有一个contents
属性。 因此,您可以对每个类别执行->contents->count()
,但不能对整个集合执行。
如果您想要每个类别的计数,只需在需要时在foreach循环中进行即可。
如果您想要与类别相关联的内容总数,则有更好的方法:
Contents::has('categories')->count();
顺便说一句,我建议将您的模型重命名为单数,因为每个实例都是其中之一,但这仅是一个建议。
您应将count用于以下类别:
$category = ContentCategories::find($id);
$category->contents()->count();
注意内容后的(),要算在SQL级别!
为什么? 简而言之,
$categories->contents
与...相同
$categories->contents()->get()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.