如何在Laravel的同一张表中插入一对多关系多数据? [英] How do I insert one to many relational multi data to same table in Laravel?

查看:170
本文介绍了如何在Laravel的同一张表中插入一对多关系多数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表结构是: id | parent_id |姓名. 我的菜单模型一对多关系是:

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’); 
         }  

我正在创建带有子菜单的菜单.例如,我必须设置具有三个子菜单的父菜单".为此,我创建了一个具有四个输入字段的表单.

I am creating menus with sub menus.For example I have to set 'Parent Menu' with three child menus.For this I have created a form with four inputs field.

<form>
     <input type="text" name="parent">
     <input type="text" name="child[]">
     <input type="text" name="child[]">
     <input type="text" name="child[]">
     </form>

现在我想同时保存父菜单及其子菜单.我试图将它们保存在数组中,但是在Laravel中不起作用. 也请解释什么是保存此数据的控制器方法. 预先感谢

Now I want to save parent menu with its child menus at the same time.I tried to save them in array but its not working in Laravel. Please also explain what would be the controller method for saving this data. Thanks in advance

推荐答案

我找到了问题的解决方案.在这里,我要发布...

I found the solution for my question.Here I am posting...

    $parent_menu = $request->input('parent');
    $parent = Menu::create(['name' =>  $parent_menu]);
    $parent->save();
    $child_menus = $request->input('child');
    foreach($child_menus as $child_menu) {
    $child = $parent->pages()->create(['name' => $child_menu]);
    $child->save();
    }

这篇关于如何在Laravel的同一张表中插入一对多关系多数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆