Answer the question
In order to leave comments, you need to log in
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);
}
}
public function categories() {
return $this->belongsTo(Category::class, 'category_id');
}
$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
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 questionAsk a Question
731 491 924 answers to any question