简体   繁体   中英

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. So you can do ->contents->count() on each category, but not on the entire collection.

If you want the count of each category, just do it inside a foreach loop when you need it.

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:

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

Beware the () after contents, to count in SQL level!

Why? In short,

$categories->contents

is the same with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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