0
votes

I have the category model where each category can be general or nesting.

Category: id parent_id title

To get children of category and all nested children of category use relation with recursion

public function children()
{
    return $this->hasMany('App\Models\Category', 'parent_id', 'id');
}

public function allChildren()
{
    return $this->children()->with('allChildren');
}

And relation for products

    public function product()
{
    return $this->belongsToMany('App\Models\Product', 'categories_products');
}

How can I get all products from base category and all nested categories?

1

1 Answers

0
votes

If you don't care about performance something like this should work (not tested) but it might obviously generate many queries in case you have very complex tree of categories.

$products = Category::getAllProducts($categoryId);

public static function getAllProducts($categoryId, $products = null)
{
  if ($products === null) {
     $products = collect();   
  }
  $category = Category::find($categoryId); 
  $products = $products->merge($category->product);
  $category->children->each(function($child) {
      $products = self::getAllProducts($child->id, $products);
  });

  return $products;
}

As alternative you could find first all the categories and then products that belong to those categories assuming you won't get hundreds of categories because it could lead to PDO bindings problems if you don't use raw queries.