我想使用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个字段,可提交给此模型标题[],说明[],question_id [] 这种形式是可重复的形式
答案 0 :(得分:0)
据我所知,您没有正确形成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);