Php 如何在laravel中正确地进行批量保存或多次保存?
请说明如何将多个数据正确插入数据库。我正在构建一个库存系统,但尝试插入数据库时出错 这就是我现在所拥有的。 Blade.phpPhp 如何在laravel中正确地进行批量保存或多次保存?,php,laravel,eloquent,Php,Laravel,Eloquent,请说明如何将多个数据正确插入数据库。我正在构建一个库存系统,但尝试插入数据库时出错 这就是我现在所拥有的。 Blade.php <form method="POST" action="{{URL::to('/new-invoice')}}"> <table class="table table-head-fixed text-nowrap" id="myTable">
<form method="POST" action="{{URL::to('/new-invoice')}}">
<table class="table table-head-fixed text-nowrap" id="myTable">
<thead>
<tr>
<th>Qty</th>
<th>Item</th>
<th>Description</th>
<th>Unit Price</th>
<th>Tax</th>
<th>Total</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="number" name="inv_qty[]" class="form-control quantity" style="width: 70px"></td>
<td>
<select name="inv_item[]" class="form-control item" style="width: 250px">
<option>Items</option>
</select>
</td>
<td><input type="text" name="inv_desc[]" class="form-control description" style="width: 400px"></td>
<td><span class="tag tag-success"><input type="text" name="inv_unit_price[]" class="form-control u_price" style="width: 150px"></span></td>
<td><span class="tag tag-success"><input type="text" name="inv_tax[]" class="form-control tax" style="width: 150px"></td>
<td><span class="tag tag-success"><input type="text" name="inv_total[]" class="form-control amount" style="width: 150px"></td>
<td>
<span><button class="btn btn-default"><i class="fa fa-trash" aria-hidden="true"></i></button></span>
<span><button type="button" onclick="myFunction()" class="btn btn-default"><i class="fa fa-plus" aria-hidden="true"></i> Add Row</button></span>
</td>
</tr>
</tbody>
</table>
<button class="btn btn-primary">Save</button>
</form>
请注意,这是我获取非法字符串偏移量“库存数量”时出现的错误。。我如何才能成功地将insert添加到数据库中来修复此问题?当前您正在循环处理请求,而不是尝试循环处理的实际数据。以下是您的请求的示例:
array:7 [▼
"_token" => "xxxxxxxxxxxxxxxxxx"
"inv_qty" => array:2 [▶]
"inv_item" => array:2 [▶]
"inv_desc" => array:2 [▶]
"inv_unit_price" => array:2 [▶]
"inv_tax" => array:2 [▶]
"inv_total" => array:2 [▶]
]
我目前无法在您共享的代码片段中看到您的Javascript函数(myFunction),但如果您将表单设置为按以下方式工作,则可以更新Javascript函数以跟踪当前索引,并在添加新行之前将所述索引调整为您的输入名称属性
例如:
<input type="number" name="items[0][inv_quantity]"/>
<input type="number" name="items[0][inv_price]"/>
<input type="number" name="items[1][inv_quantity]"/>
<input type="number" name="items[1][inv_price]"/>
<input type="number" name="items[2][inv_quantity]"/>
<input type="number" name="items[2][inv_price]"/>
如果我想插入一个字符串,请怎么办
<input type="number" name="items[0][inv_quantity]"/>
<input type="number" name="items[0][inv_price]"/>
<input type="number" name="items[1][inv_quantity]"/>
<input type="number" name="items[1][inv_price]"/>
<input type="number" name="items[2][inv_quantity]"/>
<input type="number" name="items[2][inv_price]"/>
$data = $request->all();
if(array_key_exists('items', $data)) {
foreach($data['items'] as $item) {
Invoice::insert([
'inv_quantity' => $item['inv_quantity'],
'inv_price' => $item['inv_price'],
]);
}
}