A
A
Alionides2020-10-24 10:40:37
Laravel
Alionides, 2020-10-24 10:40:37

How to display all products from a category and all subcategories?

I am trying to display all products from a category and all subcategories

Here is my category table structure:

id parent_id name
1 NULL Vehicles
2 1 Cars
3 2 Motorcycles

but I am only getting the parent and its ancillary data. I want to get information about parent and additional subscriptions.

here is my category model

public function subproducts()
{
return $this->hasManyThrough(Product::class, self::class, 'parent_id', 'category_id');
}

public function products() {
return $this->hasMany(Product::class);
}

}


here is my product

public function categories() {
return $this->belongsTo(Category::class, 'category_id');
}


and this is the controller

$category = Category::with(['products', 'subproducts'])->where('slug', $slug)->first();
$allProducts = $category->products->merge($category->subproducts);

dd($allProducts);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Popov, 2020-10-27
@DenisDangerous

Use Nested Sets
https://github.com/lazychaser/laravel-nestedset
No trees here. Stupidly by parent_id with recursion, why is it needed when there are excellent solutions.
One of the advantages of Nested Sets is the speed per sample, unlimited nesting.
Minus - resource-intensive operations for creating, deleting, moving an element

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question