[英]How do I make one to many relationship to same table in Laravel 5?
I have a table called menus.I want to retrieve menus with its child menus.But only parent menus are being retrieved.Child menus result is an empty array.我有一个名为 menus 的表。我想用它的子菜单检索菜单。但只检索父菜单。子菜单结果是一个空数组。 my table structure is: id |
我的表结构是: id | parent_id |
parent_id | name.
姓名。 My Menu model one to many relationship is:
我的菜单模型一对多关系是:
public function childMenus() {
return $this->hasMany( ‘App\Menu’, ’parent_id’);
}
public function parentMenus() {
return $this->belongsTo(‘App\Menu’, ‘parent_id’);
}
My controller Method:我的控制器方法:
public function index()
{
$menu = new Menu;
$parent_menus = $menu->where('parent_id', NULL)->get();
$sub_menus = $menu->childMenus()->get();
return View('admin',compact('$parent_menus’, ‘sub_menus’);
}
When I dive dump sub_menus dd($sub_menus) it returns an empty array.当我潜水转储 sub_menus dd($sub_menus) 它返回一个空数组。 please anyone help.
请任何人帮忙。 thanks in advance.
提前致谢。
You're fetching childMenus relation for the newly created Menu object stored in $menu variable that doesn't have any related child menus, while you should fetch chidlMenus for parent menus that already exist in your database.您正在为存储在$menu变量中的新创建的Menu对象获取childMenus关系,该对象没有任何相关的子菜单,而您应该为数据库中已经存在的父菜单获取 chidlMenus。
The easiest way to load parent menus with their child menus is to do the following (notice there is no need to create a new Menu object):加载带有子菜单的父菜单的最简单方法是执行以下操作(注意不需要创建新的 Menu 对象):
$parent_menus = Menu::with('childMenus')->where('parent_id', NULL)->get();
$parent_menus will now store collecton of all parent menus and each of them will have their child menus stored in childMenus variable. $parent_menus现在将存储所有父菜单的集合,并且每个父菜单都将其子菜单存储在childMenus变量中。 You could iterate parent and child menus with:
您可以使用以下方法迭代父菜单和子菜单:
foreach ($parent_menus as $parent) {
foreach ($parent->childMenus as $child) {
//do whatever you need with the child menu
}
}
If all you want is just a collection of all child menus, regardless of what parent they have, just do:如果你想要的只是所有子菜单的集合,不管它们有什么父菜单,只需执行以下操作:
$child_menus = Menu::whereNotNull('parent_id')->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.