dragon456101 2016-09-27 10:16
浏览 71
已采纳

如何在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. my table structure is: 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. please anyone help. thanks in advance.

  • 写回答

1条回答 默认 最新

  • dtef9322 2016-09-27 10:30
    关注

    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.

    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):

    $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. 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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大