mercredi 30 septembre 2020

Get All Products from a single category and its subcategories in laravel

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2G5PJSd
via IFTTT

Aucun commentaire:

Enregistrer un commentaire