如何从具有相同名称的多个输入字段插入到mysql

时间:2016-06-11 15:03:41

标签: laravel

所以,几个星期以后我正在学习Laravel框架,现在我想弄清楚如何在Laravel中正确提交表单,其中所有插入的字段具有相同的名称以及如何保存到数据库。所以下面是一段代码:

<tr>
    <td>
        <div class="form-group{{ $errors->has('item') ? ' has-error' : '' }}">
            <label for="item"></label>
            <input type="text" class="form-control" id="item" name="item[]" placeholder="Prekė">
        </div>
    </td>
    <td>
        <div class="form-group{{ $errors->has('quantity') ? ' has-error' : '' }}">
            <label for="quantity"></label>
            <input type="text" class="form-control quantity" name="quantity[]" placeholder="Kiekis">
        </div>
    </td>
    <td>
        <div class="form-group{{ $errors->has('price') ? ' has-error' : '' }}">
            <label for="price"></label>
            <input type="text" class="form-control price" name="price[]" placeholder="Kaina">
        </div>
    </td>
</tr>
<tr>
    <td>
        <div class="form-group{{ $errors->has('item') ? ' has-error' : '' }}">
            <label for="item"></label>
            <input type="text" class="form-control" id="item" name="item[]" placeholder="Prekė">
        </div>
    </td>
    <td>
        <div class="form-group{{ $errors->has('quantity') ? ' has-error' : '' }}">
            <label for="quantity"></label>
            <input type="text" class="form-control quantity" name="quantity[]" placeholder="Kiekis">
        </div>
    </td>
    <td>
        <div class="form-group{{ $errors->has('price') ? ' has-error' : '' }}">
            <label for="price"></label>
            <input type="text" class="form-control price" name="price[]" placeholder="Kaina">
        </div>
    </td>
</tr>

一段Laravel代码:

public function postNewOrder(Request $request)
{  
    $this->validate($request, [
        'title' => 'required',
        'item' => 'required',
        'quantity' => 'required',
        'price' => 'required',
    ]);

    Order::create([
        'user_id' => Auth::user()->id,
        'title' => $request->input('title'),
        'total' => $request->input('total'),
    ]);

    Item::create([
        'order_id' => 1,
        'position' => 1,
        'item' => $request->input('item'),
        'quantity' => $request->input('quantity'),
        'price' => $request->input('price'),
        'sum' => $request->input('sum'),
    ]);

    return redirect()->route('order.list')->with('info', 'Užsakymas sėkmingai pridėtas');
}

我知道我需要使用foreach循环,但我不知道如何执行此操作。

提前感谢您的帮助!

编辑: 这是一个例子: https://jsfiddle.net/xqy6qafk/3/

点击“Pridėtiprekę”按钮。表格中添加了一行。所以现在我想在你点击按钮“Išsaugoti”时将这两行插入到数据库中,但是我不知道怎么做。

1 个答案:

答案 0 :(得分:0)

你是用jQuery动态添加行的,所以我想最好的方法是用jQuery从动态创建的行中收集数据,然后将这些数据发送到控制器。

在控制器中,如果准备了JSON数据,您只需将其转换为具有json_decode()函数的数组(行数组)数组。

执行此操作后,您可以使用单个子句插入多行而不使用任何foreach循环:

Item::create($arrayOfArrays); // This will insert multiple items
相关问题