I have 4 tables - foods, food_categories, food_subcategories and categories_to_foods.
The same food item can belong to several categories and subcategories.
I can't understand how to get results in a format like categories -> subcategories -> foods.
Also, I would like there to be category_id and subcategory_id on foods array and category_id on subcategories array.
How do I need to set up relationships so I could use with() like this - a categories array with subcategories array (inside) with foods array (inside).
// I know this is not correct...
$categories_wiht_foods = Categories::with('subcategories.foods')->get();
categories: [
{
id: 1,
description: 'First category',
subcategories: [
{
id: 1,
description: 'First subcategory',
category_id: 1,
foods: [
{
id: 1,
description: 'Pizza',
category_id: 1,
subcategory_id: 1,
}
]
}
]
},
]
Foods table
+----+-------------+
| id | description |
+----+-------------+
| 1 | Pizza |
+----+-------------+
Categories table
+----+----------------+
| id | description |
+----+----------------+
| 1 | First category |
+----+----------------+
Subcategories table
+----+-------------------+
| id | description |
+----+-------------------+
| 1 | First subcategory |
+----+-------------------+
categories_to_foods table
+----+---------+-------------+----------------+
| id | food_id | category_id | subcategory_id |
+----+---------+-------------+----------------+
| 1 | 1 | 1 | 1 |
+----+---------+-------------+----------------+
| 2 | 1 | 2 | 14 |
+----+---------+-------------+----------------+