laravel eloquent relationships count

Solutions on MaxInterview for laravel eloquent relationships count by the best coders in the world

showing results for - "laravel eloquent relationships count"
Josué
19 Apr 2019
1class Category extends Model
2{
3
4    protected $appends = [
5        'articleCount'
6    ];
7
8    public function articles()
9    {
10        return $this->hasMany(Article::class);
11    }
12
13    public function children()
14    {
15        return $this->hasMany(Category::class, 'parent_id');
16    }
17
18    public function childrenArticles()
19    {
20        return $this->hasManyThrough(Article::class, Category::class, 'parent_id');
21    }
22
23    public function getArticleCountAttribute()
24    {
25        return $this->articles()->count() + $this->childrenArticles()->count();
26    }
27}
28