0

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 !

Paul J.K
  • 603
  • 1
  • 4
  • 13
  • There are two ways, High memory and process way but easy, Low memory and process way but hard. Easy way: you can use recursive function. Hard way: write complex sql query. – Sohag Hasan Aug 12 '22 at 18:06
  • In your subCategories() relation, maybe you can do `return $this->hasMany(self::class, 'parent')->with('subCategories')->count();` ? – Jérôme Aug 12 '22 at 18:11
  • Does this answer your question? [How to create a MySQL hierarchical recursive query?](https://stackoverflow.com/questions/20215744/how-to-create-a-mysql-hierarchical-recursive-query) – nice_dev Aug 12 '22 at 18:12

1 Answers1

0

Try This in your category model

return $this->hasMany(self::class, 'parent')->with('subCategories')->count();
Laravel
  • 133
  • 11