在这种情况下,我想通过菜单ID从关系中获取所有数据。我怎样才能做到这一点?
我已经尝试过在线搜索,但是找不到类似的情况...请帮助...
这是我的模型:
菜单
class Menu extends Model
{
protected $fillable = [
'name', 'img', 'status', 'views'
];
public function stores()
{
return $this->belongsToMany(Store::class, 'store_menu');
}
public function categories()
{
return $this->hasMany(Category::class);
}
}
类别
class Category extends Model
{
protected $fillable = ["img", "title", "description", "status", "menu_id"];
public function items()
{
return $this->hasMany(Item::class);
}
public function menu()
{
return $this->belongsTo(Menu::class, 'menu_id');
}
}
项目
class Item extends Model
{
protected $fillable = [
'name', 'img', 'price', 'status', 'view', 'category_id'
];
public function category()
{
return $this->belongsTo(Category::class, 'category_id');
}
}
通过执行以下操作,我只能设法获得菜单的类别:
$id = $request->menu_id;
$menu = Menu::find($id);
$categories = $menu->categories;
dd(menu);
当前结果:
"data": {
"id": 1,
"name": "Menu name",
{
"id": 1,
"title": "Category 1 name",
"menu_id": 1,
},
{
"id": 2,
"title": "Category 1 name",
"menu_id": 1,
},
{
"id": 3,
"title": "Category 1 name",
"menu_id": 1,
}
]
},
结果我想得到:
"data": {
"id": 1,
"name": "Menu Name",
"categories": [
{
"id": 1,
"title": "Category 1 name",
"menu_id": 1,
"items":[
{
"id": 1,
"name": "Item 1 Name"
},
{
"id": 2,
"name": "Item 2 Name"
},
]
},
{
"id": 2,
"title": "Category 2 name",
"menu_id": 1,
"items":[
{
"id": 1,
"name": "Item 3 Name"
},
{
"id": 2,
"name": "Item 4 Name"
},
]
},
{
"id": 3,
"title": "Category 3 name",
"menu_id": 1,
"items":[
{
"id": 1,
"name": "Item 5 Name"
},
{
"id": 2,
"name": "Item 6 Name"
},
]
}
]
},
感谢您的帮助。
最佳答案
您可以利用预先加载来加载嵌套关系:
$menu = Menu::with('categories.items')->find($id);
关于laravel - Laravel-如何从两个模型中获取数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58500143/