【发布时间】:2021-11-13 19:44:21
【问题描述】:
我正在尝试使用数组将数据插入数据透视表order_serrvice。我遵循以下代码:https://blog.quickadminpanel.com/master-detail-form-in-laravel-jquery-create-order-with-products/
订单控制器:
$order = Order::create($data);
$services = $request->input('services', []);
$quantities = $request->input('quantities', []);
for ($service = 0; $service < count($services); $service++) {
if ($services[$service] != '') {
$order->services()->attach($services[$service], ['quantity' => $quantities[$service]]);
}
}
刀片页面:
<tbody>
<tr id='addr0'>
<td>1</td>
<td>
<select name="services[]" class="form-control">
<option value="">-- choose service --</option>
@foreach ($services as $service)
<option value="{{ $service->id }}">
{{ $service->name }} (${{ number_format($service->price, 2) }})
</option>
@endforeach
</select>
{{--<input type="text" name='service[]' placeholder='Enter Product Name' class="form-control"/>--}}
</td>
<td><input type="number" name='qty[]' placeholder='Enter Qty' class="form-control qty" step="0" min="0"/></td>
<td><input type="number" name='price[]' placeholder='Enter Unit Price' class="form-control price" step="0.00" min="0"/></td>
<td><input type="number" name='total[]' placeholder='0.00' class="form-control total" readonly/></td>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>
与dd($request):
"services" => array:2 [▼
0 => "1"
1 => "2"
]
"qty" => array:2 [▼
0 => "27"
1 => "2"
]
"price" => array:2 [▼
0 => "489"
1 => "4"
]
"total" => "23647.69"
"sub_total" => "13211.00"
"vat" => "10436.69"
dd($services[$service]):
"1"
错误:
ErrorException 未定义的偏移量:0 $order->services()->attach($services[$service], ['quantity' => $quantities[$service]]);
有人可以帮忙吗?
【问题讨论】:
-
您使用的是
$request->input('quantities', []),但您的表单有<input ... name='qty[]'。 数量 != 数量。我投票结束这是一个错字。