Answers for "laravel eloquent relationships count"

PHP
0

laravel eloquent relationships count

class Category extends Model
{

    protected $appends = [
        'articleCount'
    ];

    public function articles()
    {
        return $this->hasMany(Article::class);
    }

    public function children()
    {
        return $this->hasMany(Category::class, 'parent_id');
    }

    public function childrenArticles()
    {
        return $this->hasManyThrough(Article::class, Category::class, 'parent_id');
    }

    public function getArticleCountAttribute()
    {
        return $this->articles()->count() + $this->childrenArticles()->count();
    }
}
Posted by: Guest on September-14-2021

Code answers related to "laravel eloquent relationships count"

Browse Popular Code Answers by Language