简体   繁体   English

Laravel依靠AboutToMany关系

[英]Laravel get count on belongsToMany relationship

in my project i have two model as: 在我的项目中,我有两种模型:

Contents: 内容:

class Contents extends Model
{
    protected $table = 'contents';
    protected $guarded = ['id'];

    public function categories()
    {
        return $this->belongsToMany(ContentCategories::class);
    }
}

and Categories: 和类别:

class ContentCategories extends Model
{
    protected $table = 'contents_categories';
    protected $guarded = ['id'];

    public function contents()
    {
        return $this->belongsToMany(Contents::class);
    }
}

in my project each content must be have one or more category and i want to get count of content that they are assigned to categories by this code: 在我的项目中,每个内容都必须具有一个或多个类别,我想通过此代码将它们分配给类别的内容计数:

$categories = ContentCategories::with('contents');
dd($categories->contents->count());

unfortunately i get this error: 不幸的是我得到这个错误:

"Undefined property: Illuminate\Database\Eloquent\Builder::$contents"

how can i resolve this problem? 我该如何解决这个问题? thanks 谢谢

Your $categories variable is a collection in which each category has a contents attribute. $categories变量是一个集合,其中每个类别都有一个contents属性。 So you can do ->contents->count() on each category, but not on the entire collection. 因此,您可以对每个类别执行->contents->count() ,但不能对整个集合执行。

If you want the count of each category, just do it inside a foreach loop when you need it. 如果您想要每个类别的计数,只需在需要时在foreach循环中进行即可。

If you want the total number of contents that have connections to categories, there's a better way: 如果您想要与类别相关联的内容总数,则有更好的方法:

Contents::has('categories')->count();

As an aside, I would suggest renaming your models to singular, since each instance is one of something, but that's just a suggestion. 顺便说一句,我建议将您的模型重命名为单数,因为每个实例都是其中之一,但这仅是一个建议。

You should use count for one category as follows: 您应将count用于以下类别:

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

Beware the () after contents, to count in SQL level! 注意内容后的(),要算在SQL级别!

Why? 为什么? In short, 简而言之,

$categories->contents

is the same with 与...相同

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM