php - 如何修复 Laravel 批量插入记录仅将第一条记录保存到数据库
问题描述
我正在尝试将多条记录保存到数据库。我认为从前端视图提交数组一定有问题。
首先,我的行是用 jquery 动态生成的。我试过 var_dumping 请求,它只给了我第一行。我在每个输入字段名称中的名称中添加了 []。
我的视图中的一些输入字段
<td width="15%">
<select class="form-control select2 item_id" name="item_id[]" required>
<option></option>
</select>
</td>
<td width="10%">
<select class="form-control select2 location_id" name="location_id[]" required>
<option></option>
</select>
</td>
<td width="20%">
<input type="text" class="form-control package" name="package[]" required>
</td>
控制器
$receive = new Receive();
$receive->datetime = $request->datetime;
$receive->user_id = $request->user_id;
$receive->truck_id = $request->truck_id;
$receive->from = $request->from;
$receive->condition = $request->condition;
$receive->space = $request->space;
dd($request->all());
if($receive->save()) {
$id = $receive->id;
foreach($request->item_id as $key=>$it) {
$data = array('receive_id'=>$id,
'item_id'=>$request->item_id [$key],
'location_id'=>$request->location_id [$key],
'package'=>$request->package [$key],
'quantity'=>$request->quantity [$key],
'note'=>$request->note [$key],
);
ItemReceive::create($data);
}
return back()->with('success', 'Received Items successfully');
}
return back()->with('success', 'Received successfully.');
我除了将数组数据保存到数据库中,但只有第一行进入后端。
解决方案
我不想在 DB 中插入单个条目,但是,我更愿意创建一个数组并将该数组传递给 insert,如下所示:
尝试用以下代码替换您的代码:
$now = date('Y-m-d H:i:s');
//you could also try
//$now = Carbon::now();
$arr = [];
foreach($request->item_id as $key=>$it) {
$arr[] = array('receive_id'=>$id,
'item_id'=>$request->item_id[$key],
'location_id'=>$request->location_id[$key],
'package'=>$request->package[$key],
'quantity'=>$request->quantity[$key],
'note'=>$request->note[$key],
'created_at' => $now,
'updated_at' => $now
);
}
ItemReceive::create($arr);
//make sure you have assigned a correct key in `$fillable` array in your `ItemReceive` model.
编辑:1
尝试添加multiple
以选择:
<select multiple name="bdhdh">
<option>hdjdjd</option>
</select>
推荐阅读
- compression - 用于压缩的二元决策图等工具
- excel - VBA,excel:删除/插入行,没有错误,没有结果
- c# - AddorUpdate 字典中的数据
- python - Pytest隐藏了一些参数值
- selenium-webdriver - selenium c# 边缘浏览器:'意外错误。未知错误'
- r - 将列添加到数据框中
- spring-boot - 使用接口投影方法名称呈现结果集列名称时出现问题 - 从多个表中获取多个列
- conda - conda 使用更新版本的 glibc
- python - 在python中根据名称和时间聚合数据
- css - 如何在浏览器中更改简单的长方形/线条的长度、粗细和曲率?