2017-08-07 76 views
0

我正在使用产品&价格模型。我的产品表有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'); 
} 

enter image description here

当然我的代码抛出我所得到的,当我转储请求数据写入发生此错误 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')

我该如何解决这个问题?

回答

1
foreach ($request->input('cost') as $key=>$cost) { 

    Price::create([ 
     'product_id' => $request->product_id[$key], 
     'date' => Carbon::now(), 
     'cost' => $cost, 
     'trend' => 0 
    ]); 
} 

,你可以看到整个阵列中的产品ID获得通过,所以你需要提及,而您需要插入

一个特定的ID
1

您可以使用索引或键/值对的概念,在输入的数组是这样的:

试试这个,

foreach ($request->input('cost') as $key=>$cost) { 
    Price::create([ 
     'product_id' => $request->product_id[$key], 
     'date' => Carbon::now(), 
     'cost' => $cost, 
     'trend' => 0 
    ]); 
} 

这将节省您的数据,如

1 -> 14.05 
2 -> 13.75 
3 -> 12.99 

希望你明白。

相关问题