我正在尝试将一些数据发布到应用程序中的Restful API中,但是当JSON包含一组以上数据时,我不会成功。
这是我的JSON示例:
"data": [ {
"client_id": "3",
"veiculo_id": "3",
"carreta1_id": "3",
"carreta2_id": "3",
"motorista1_id": "3",
"motorista2_id": "3",
"embarcador_id": "3",
"inicioprevisao": "2018-10-10 11:00:00",
"fimprevisao": "2018-10-10 18:00:00",
"nroliberacao": "3"
},
{
"client_id": "4",
"veiculo_id": "4",
"carreta1_id": "4",
"carreta2_id": "4",
"motorista1_id": "4",
"motorista2_id": "4",
"embarcador_id": "4",
"inicioprevisao": "2018-10-10 11:00:00",
"fimprevisao": "2018-10-10 18:00:00",
"nroliberacao": "4"
}
] }
这是我的控制器:
public function storeapi(Request $request)
{
$array = $request->all();
foreach ($array['data'] as $row) {
return Sm::create([
'client_id' => $row['client_id'],
'veiculo_id' => $row['veiculo_id'],
'carreta1_id' => $row['carreta1_id'],
'carreta2_id' => $row['carreta2_id'],
'motorista1_id' => $row['motorista1_id'],
'motorista2_id' => $row['motorista2_id'],
'embarcador_id' => $row['embarcador_id'],
'inicioprevisao' => $row['inicioprevisao'],
'fimprevisao' => $row['fimprevisao'],
'nroliberacao' => $row['nroliberacao']
]);
}
}
通过这种方式,我只有第一个块放在数据库中,而我需要两个块。 我关注本文,但无法正常工作。 laravel 5.6 bulk inserting json data
答案 0 :(得分:0)
该问题正在发生,因为您在return
循环中使用了foreach
。我猜您正在这样做是因为您想return
插入元素的ID,因此最好像这样遍历:
$array = $request->all();
$insertedIds = [];
foreach ($array['data'] as $row) {
$newSm = Sm::create([
'client_id' => $row['client_id'],
'veiculo_id' => $row['veiculo_id'],
'carreta1_id' => $row['carreta1_id'],
'carreta2_id' => $row['carreta2_id'],
'motorista1_id' => $row['motorista1_id'],
'motorista2_id' => $row['motorista2_id'],
'embarcador_id' => $row['embarcador_id'],
'inicioprevisao' => $row['inicioprevisao'],
'fimprevisao' => $row['fimprevisao'],
'nroliberacao' => $row['nroliberacao']
]);
$insertedIds[] = $newSm->id;
}
//Now we can return an array with the inserted elements' IDs
//In this case, since this is coming from a JSON, we'll answer the same way.
return response()->json($insertedIds);