我的表结构是: id | parent_id |名称。 我的菜单模型一对多的关系是:
public function childMenus() {
return $this->hasMany( ‘App\Menu’, ’parent_id’);
}
public function parentMenus() {
return $this->belongsTo(‘App\Menu’, ‘parent_id’);
}
我正在使用子菜单创建菜单。例如,我必须使用三个子菜单设置“父菜单”。为此,我创建了一个包含四个输入字段的表单。
<form>
<input type="text" name="parent">
<input type="text" name="child[]">
<input type="text" name="child[]">
<input type="text" name="child[]">
</form>
现在我想同时保存父菜单及其子菜单。我试图将它们保存在数组中,但它不能在Laravel中工作。 还请解释保存此数据的控制器方法。 提前致谢
答案 0 :(得分:0)
您可以使用saveMany
方法将多个子项附加到父级。
// Assuming whatever goes into the text box goes in the "name" field.
$parent = new \App\Parent();
$parent->name = \Input::get('name');
$parent->save();
$children = [];
foreach (Input::get('child') as $child) {
$children = new \App\Child([
'name' => $child
]);
}
$parent->childMenus()->saveMany($children);
答案 1 :(得分:0)
我找到了问题的解决方案。我在发帖...
$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();
}