【问题标题】:How to insert a multidimensional array in a database using laravel如何使用 laravel 在数据库中插入多维数组
【发布时间】:2016-07-29 16:21:53
【问题描述】:

我正在使用 laravel 开发电子商务应用程序。当客户单击结帐按钮时,我想保存购物车值订单和订单详细信息表。一份订单有很多订单详情。我可以插入订单值:customerid、orderdate、shipdate、orderamount…… 但正如我所提到的,一份订单有很多订单详情。这是我的订单详情表:

**Id 
ordereid
product_id
price
quantity
price
amount**

每个订单都有这么多产品:

Array ( [productids] => Array ( [0] => 6 [1] => 11 [2] => 7 [3] => 1 ) [quantity] => Array ( [0] => 2[1]=>1[2]=>3) [price] => Array ( [0] => 750.00 [1] => 456.00 [2] => 200.00 [3] => 700.00 ) [amount] => Array ( [0] => 1500 [1] => 456 [2] => 600 [3] => 1400 ) )

这就是我所做的,并且得到了数组到字符串的转换异常

        for($i=0; $i < count($product); $i++)
        {
 $order_details =new Order_detail;  
    $order_details->order_id = $orders->id;        
    $order_details->product_id=$product['product_id'][$i];        
    $order_details->quantity=$product['quantity'][$i];    
    $order_details->unit_price=$product['price'][$i];        
    $order_details->amount=$product[amount][$i];

    $order_details->save();

       }

我也尝试将每个子数组包装在 foreach 循环中,但在订单详细信息中只插入了一个原始数据 例如,如果客户订单购物车中有三件产品,则应在订单详细信息中插入三行:

    Id  
    ordered
    productid
    quantity
    price    
   amount

任何帮助。

【问题讨论】:

    标签: laravel


    【解决方案1】:

    这是我在这种情况下会做的事情。

    第一步:从数组中抓取对象

    $order_details = [];
    for($i= 0; $i < count($product); $i++){
        $order_details[] = [
            'order_id' => $orders->id,
            'product_id' => $product['product_id'][$i],
            'quantity' => $product['quantity'][$i],
            'unit_price' => $product['price'][$i],
            'amount' => $product['amount'][$i],
        ];
    }
    

    第 2 步:插入表格

    \DB::table('order_details')->insert($order_details);
    

    这就是你所需要的, 更多关于insert方法可以找到here

    【讨论】:

    • 非常感谢您的帮助。我如何在 foreach($i= 0; 语法错误,意外的 ';' 处遇到语法错误。
    • 哦,对不起,这是一个 for 语句,而不是 foreach,我已经修改了我的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 2014-11-01
    • 2017-10-04
    • 2019-08-29
    • 2020-07-12
    • 2018-01-14
    相关资源
    最近更新 更多