我正在使用產品&價格模型。我的產品表有ID和名稱列,而我的價格表有ID,product_id,成本和日期列。價格表上的product_id引用產品表上的id。我的表單爲每個產品顯示一個字段,以便用戶隨時輸入價格。我的挑戰是如何處理請求數據,以便價格符合product_id。下面是我的代碼至今動態添加表單輸入字段並使用Laravel 5存儲值
形式
<form class="form-horizontal" method="POST" action="{{ url('/home/prices') }}">
{{ csrf_field() }}
@if(isset($products) && !empty($products))
@foreach($products as $product)
<div class="form-group">
<div>
<input type="hidden" class="form-control" name="product_id[]" value="{{ $product->id }}">
</div>
</div>
<div class="form-group">
<label class="col-sm-2" for="{{ $product->name }}">{{ ucwords($product->name) }}</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="cost[]">
</div>
</div>
@endforeach
@else
Sorry, no product available currently.
@endif
<button type="submit" class="btn btn-default">Add</button>
</form>
PriceController
public function store(Request $request)
{
//dd($request);
foreach ($request->input('cost') as $cost) {
Price::create([
'product_id' => $request->product_id,
'date' => Carbon::now(),
'cost' => $cost,
'trend' => 0
]);
}
return redirect('/home');
}
當然我的代碼拋出我所得到的,當我轉儲請求數據寫入發生此錯誤 at Builder->insertGetId(array('product_id' => array('1', '2', '3'), 'date' => object(Carbon), 'cost' => '14.05', 'trend' => 0, 'updated_at' => '2017-08-07 11:21:47', 'created_at' => '2017-08-07 11:21:47'), 'id')
我該如何解決這個問題?