I have a Category model in which has children categories which has products... getting the total amount of products along with the children is easy. But what about getting the parent categories total amount which is the sum of all children categories of this single parent?
Here is the App\Category model:
public function products()
{
return $this->hasMany(Product::class, 'category_id');
}
public function parent()
{
return $this->hasOne(Category::class, 'id', 'parent_id');
}
public function children()
{
return $this->hasMany(Category::class, 'parent_id', 'id');
}
public function scopeTotalShirts($query)
{
return $query->where('slug', 'shirts')->first()->children->each->products()->count();
}
A shirt would have child categories such as T-Shirt, Long Sleeve, Graphic, etc.
I want to get the total of those children categories so it all adds up in the Shirts (parent) category.
Is there some elegant way to do this besides querying up the children categories and getting the count?
Thank you!