【问题标题】:PHP Laravel insert to table using foreachPHP Laravel 使用 foreach 插入表
【发布时间】:2022-01-28 13:07:40
【问题描述】:

所以我有这个帖子请求数据

 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_idproduct_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>

   

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    巴勃罗。此致。您的 product_price 是一个数组,因此您不能这样做:

    $order-&gt;product_price = $input['product_price'];

    我会在包含表单的视图中采用不同的方法,以确保 product_id 数组与 product_price 的大小/顺序匹配(更好的可读性/维护性)。

    但是要解决您提出的问题,您需要获取product_id的key,并使用该key来检索价格,如下所示:

    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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-23
      • 2017-07-08
      • 1970-01-01
      • 2016-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-08
      相关资源
      最近更新 更多