我正在使用产品和价格模型。我的产品表有一个 id 和名称列,而我的价格表有一个 id、product_id、cost 和 date 列。价格表中的 product_id 引用了产品表中的 id。我的表单为每个产品显示一个字段,以便用户不时输入价格。我的挑战是如何处理请求数据,以便价格与 product_id 相对应。以下是我到目前为止编写的代码
表格
<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>
价格 Controller
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');
}
当然我的代码会抛出这个错误
在 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')
我该如何解决这个问题?
最佳答案
foreach ($request->input('cost') as $key=>$cost) {
Price::create([
'product_id' => $request->product_id[$key],
'date' => Carbon::now(),
'cost' => $cost,
'trend' => 0
]);
}
如您所见,整个数组都在产品 ID 中传递,因此您需要提及需要插入的特定 ID
关于php - 使用 Laravel 5 动态添加表单输入字段和存储值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45545794/