Laravel 获得对 belongsToMany 关系的计数

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();

顺便说一句,我建议将您的模型重命名为单数,因为每个实例都是某物的一个,但这只是一个建议。

您应该对一个类别使用计数,如下所示:

$category = ContentCategories::find($id);
$category->contents()->count();

注意内容后面的(),算在SQL级!

为什么?简而言之,

$categories->contents

相同
$categories->contents()->get()