I have three tables named as Users, Menu items, Category
Users table:
+-----------------------+
| Users |
+====+======+===========+
| id | name | type |
+----+------+-----------+
Restaurant table:
+-----------------------+
| Restaurant |
+====+======+===========+
| id | name | user_id |
+----+------+-----------+
Menu items table:
+------------------------------------------+
| Menu_items |
+====+======+==============================+
| id | cat_id | user_id | restaurant_id |
+----+------+------------------------------+
Category table:
+-----------------------+
| categories |
+====+======+===========+
| id | name |
+----+------+-----------+
And my relationships model functions are here.
Restaurant model
class Restaurants extends Model
{
public $table = 'restaurants';
public function getFoodItems()
{
return $this->hasMany('App\Models\Menuitems','restaurant_id','id');
}
public function getCatGroup()
{
return $this->getFoodItems()->groupBy('main_category');
}
}
User model
class Chefs extends Model
{
public $table = 'users';
public function restaurants()
{
return $this->hasMany(Restaurants::class, 'vendor_id', 'id');
}
public function getVendorFoodDetails()
{
return $this->hasMany('App\Models\Menuitems','vendor_id','vendor_id');
}
}
Category model
class Category extends Model
{
public $table = 'categories';
public function menuitems()
{
return $this->hasMany('App\Models\Menuitems', 'main_category', 'id');
}
}
Menu items model
class Menuitems extends Model
{
protected $table = "menu_items";
public function categories()
{
return $this->belongsTo(Category::class, 'main_category', 'id');
}
}
and my response should be something like this below.
{
"id": 13,
"name": "Vendor",
"restaurants": [
{
"id": 3,
"vendor_id": 13,
"name": "Restaurant Name",
"get_cat_group": [
{
"id": 1,
"main_category": 1,
"categories": {
"id": 1,
"name": "test11111",
"menuitems": [
{
"id": 1,
"name": "Masala test",
},
{
"id": 8,
"name": "Masala Channa"
}
]
}
},
{
"id": 7,
"main_category": 2,
"categories": {
"id": 2,
"name": "tests2",
"menuitems": [
{
"id": 7,
"name": "Masala Channa"
}
]
}
}
]
}
]
}
How should I reach this can some one please guide me.
Use 'with' to model when select to make return object have data that you refer to
Restaurants::with('Menuitems')->get();
but if you want to nested the relation use.(dot) in with
Restaurants::with('Menuitems.Categories')->get();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.