首页 > 解决方案 > 如何修复 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.');

我除了将数组数据保存到数据库中,但只有第一行进入后端。

标签: phplaraveleloquentquery-builder

解决方案


我不想在 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>

推荐阅读