Reputation: 53
I have 4 tables similar to this:
items (id)
subcategories (id | category_id)
item_subcategory (item_id | subcategory_id) --pivot table
categories (id)
The items and subcategories are connected to the pivot table with many to many relationship. How can I get all the items under each categories? Below is an example.
Upvotes: 0
Views: 1247
Reputation: 1266
There can be 3 ways we could use from my perspective, I'll share all.
Category::with(['subcategories' => function ($query) {
$query->whereHas('items');
}])->get();
It will get all the subcategories first, then the related items something like that =>
[{
"id": 1,
"title": "Category 1",
"subcategories": [{
"id": 1,
"category_id": 1,
"title": "Subcategory 1",
"items": [{
"id": 1,
"title": "Item 1",
"pivot": {
"subcategory_id": 1,
"item_id": 1
}
}]
}]
}]
public function items()
{
return $this->belongsToMany(Item::class, ItemSubcategory::class);
}
It will allow you to directly fetch products without loading subcategories first, something like that.
[{
"id": 1,
"title": "Category 1",
"items": [{
"id": 1,
"title": "Item 1",
"pivot": {
"category_id": 1,
"item_id": 1
}
}]
}]
public function items()
{
return $this->hasManyThrough(Item::class, ItemSubcategory::class, null, 'id', null, 'item_id');
}
Upvotes: 2
Reputation: 11
I don't understand completely but maybe this will be a solution for you, in your model
public function Categories()
{
return $this->hasMany(Category::class,'id', 'categoryID');
}
Upvotes: 0