2017-08-07 74 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 

希望你明白。

相關問題