所以我有這個帖子請求資料
array:6 [▼
"_token" => "oZ5OjnWU4svOPPFXMrzkDIBau92yIxd7l1Onn1EN"
"orderId" => "2"
"product_id" => array:3 [▼
0 => "111"
1 => "222"
2 => "333"
]
"product_price" => array:3 [▼
0 => "150.00"
1 => "1800.00"
2 => "800.50"
]
"discount" => "10.00"
"status" => "SUCCESS"
]
我正在嘗試使用此代碼將其保存到我的表中。
public function upsellStore( Request $request ) {
$input = $request->all();
foreach($input['product_id'] as $id ) {
$order = new OrderProduct;
$order->orderid = $input['orderId'];
$order->discount = $input['discount'];
$order->status = $input['status'];
$order->product_id = $id;
$order->product_price = $input['product_price'];
$order->save();
}
return $order;
}
但是我不確定如何保存它。product_id并且product_price應該對齊,所以這個保存的輸出應該是這樣的
<table>
<tbody>
<tr>
<th>ID</th>
<th>Product ID</th>
<th>Price</th>
<th>Discount</th>
<th>Status</th>
</tr>
</tbody>
<tbody>
<tr>
<td>1</td>
<td>111</td>
<td>150.00</td>
<td>10.00</td>
<td>SUCCESS</td>
</tr>
<tr>
<td>1</td>
<td>222</td>
<td>1800.00</td>
<td>10.00</td>
<td>SUCCESS</td>
</tr>
<!-- and so on... -->
</tbody>
</table>
Run code snippetHide resultsExpand snippet
uj5u.com熱心網友回復:
巴勃羅。最好的祝福。您的 product_price 是一個陣列,因此您不能這樣做:
$order->product_price = $input['product_price'];
我會在包含表單的視圖中采用不同的方法,以確保 product_id 陣列與 product_price 的大小/序列匹配(更好的可讀性/維護性)。
但是要解決您提出的問題,您需要獲取 product_id 的密鑰,并使用該密鑰來檢索價格,如下所示:
foreach($input['product_id'] as $key => $id ) { $order = new OrderProduct; $order->orderid = $input['orderId']; $order->discount = $input['discount']; $order->status = $input['status']; $order->product_id = $id; $order->product_price = $input['product_price'][$key]; $order->save(); }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/423110.html
標籤:
