我想使用 createMany 创建多记录,如何在没有数据复制的情况下将数组插入到此方法?
public function update(Request $request, Question $question)
{
$options = $request->only('title', 'description', 'question_id');
$options_data = [];
foreach ($options as $key => $value) {
$options_data[] =[
'title' => $options[$key],
'description' =>$options[$key],
'question_id' => $options[$key]
];
}
$question->options()->createMany($options_data);
结果:dd()
我提交了 2 条包含 3 个字段的记录
array:3 [▼
0 => array:3 [▼
"title" => array:2 [▼
0 => "option one"
1 => "option two"
]
"description" => array:2 [▼
0 => "option one"
1 => "option two"
]
"question_id" => array:2 [▼
0 => "option one"
1 => "option two"
]
]
1 => array:3 [▼
"title" => array:2 [▼
0 => "option description"
1 => "option two description"
]
"description" => array:2 [▼
0 => "option description"
1 => "option two description"
]
"question_id" => array:2 [▼
0 => "option description"
1 => "option two description"
]
]
2 => array:3 [▼
"title" => array:2 [▼
0 => "14"
1 => "14"
]
"description" => array:2 [▼
0 => "14"
1 => "14"
]
"question_id" => array:2 [▼
0 => "14"
1 => "14"
]
]
]
我的表单有 3 个字段用于提交到此模型 title[]、description[]、question_id[]
该表格是可重复的表格
据我所知,你没有正确形成 html 文件。你的 html 文件应该是这样的
<input type="text" name="items[1][title]">
<input type="text" name="items[1][description]">
<input type="text" name="items[1][question_id]">
<input type="text" name="items[2][title]">
<input type="text" name="items[2][description]">
<input type="text" name="items[2][question_id]">
$options = $request->only('items');
$options_data = [];
foreach ($options as $key => $value) {
$options_data[] = $value;
}
$question->options()->createMany($options_data);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)