如何使用Laravel在数据库中插入多维数组 [英] How to insert a multidimensional array in a database using laravel
问题描述
我正在使用laravel开发电子商务应用程序.当客户单击结帐按钮时,我想保存购物车值订单和订单明细表.一个订单有许多订单详细信息.我可以插入订单值:客户编号,订单日期,发货日期,订单金额…… 但是正如我已经提到的,一个订单有很多订单细节.这是我的订单明细表:
I am working on a eCommerce app in laravel. I want to save shopping cart values order and order details tables when the customer clicks checkout button. One order has many order details. I can insert order values: customerid, orderdate,shipdate,orderamount…… But as I have mentioned, one order have many orderdetails. This is my order details table:
**Id
ordereid
product_id
price
quantity
price
amount**
每个订单都有很多产品,
Each order have many products as so:
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 ) )
这就是我所做的,并且正在将Array转换为字符串转换异常
This is what I have done and am getting Array to string conversion exception
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循环中,但是在订单详细信息中仅插入了一个原始文件 例如,如果客户订单购物车有三种产品,则应该在订单明细中插入三行:
I have also tried to wrap each sub-array in foreach loop but only a single raw is inserted in the order details For example if the customer order shopping cart has three products, three rows should be inserted into the order details with:
Id
ordered
productid
quantity
price
amount
任何帮助.
推荐答案
在这种情况下,我会这样做.
Here's what I'd do in this situation.
$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);
这就是您所需要的, 可以在此处
That's all you would need, more on the insert method can be found here
这篇关于如何使用Laravel在数据库中插入多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!