I want to get all products from a category and its subcategory too. But I keep getting the products of the parent and its child category, But neglecting its Grand-Children`
This is my Category structure:
| id | parent_id | name |
|----|-----------|-------------|
| 1 | NULL | Vehicles |
| 2 | 1 | Cars |
| 3 | 2 | Toyota |
Category model
public function parent() {
return $this->belongsTo(self::class,'parent_id','id');
}
public function children() {
return $this->hasMany(self::class, 'parent_id', 'id');
}
public function products() {
return $this->hasMany(Product::class);
}
Product model
public function categories() {
return $this->hasMany(Category::class);
}
In the Controller, my attempt we have
$categoryIds = Category::where('parent_id', $parentId = Category::where('type', 'Vehicle')
->value('id'))
->pluck('id')
->push($parentId)
->all();
Product::whereIn('category_id', $categoryIds)->get();
But like I said, this doesn't get me the products of the grand-children of the parent or even the great-grand children of the category. How can I achieve this?
Thanks.
Someone suggested hasManyThrough
but I don't know how to go about this.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire