I have table category
like this:
id name parent
1 A 0
2 B-1 1
3 B-2 1
4 C-1 2
5 C-2 3
In model Category
public function subCategories()
{
return $this->hasMany(self::class, 'parent')->with('subCategories');
}
Note:
Category A has 2 subcategories (B-1, B-2) 1st-level
B-1 has a subcategory is C-1 2nd-level
B-2 has a subcategory is C-2 3rd-level
Only
category is at 3rd-level
has relationship with product
Example:
- Category C-1 has 3 products
- Category C-2 has 5 products
How to calculate category has how many products that related ?
Expected
- Category A : 8 products (2 sub B-1, B-2)
- Category B-1: 3 products (C-1)
- Category B-2: 5 products (C-2)
- Category C-1: 3 products
- Category C-2: 5 products
I'm pulling my hair out this problem . Any ideas will be also respected . Thanks for all !