我有两张表来下订单。在我的orders
表中,我包含订单的主要详细信息,在我的order_item
表中,我有订购的每个项目的详细信息。这是我的相同代码:
$order = new Order();
$order->user_id = $user->id;
if(!$order->save()){
return response()->json([
'message' => 'Unable to place your order. Try again.'
], 500);
}
$items = Cart_Item::where('user_id', $user->id)->get();
if($items->isEmpty()){
return response()->json([
'message' => 'Kindly add items to the cart before placing an order.'
], 500);
}
$items = $items->map(function ($item, $key) {
$product = Product::where('id', $item->product_id)->first();
$order_item = new Order_Item();
$order_item->order_id = $order->id;
$order_item->product_id = $item->product_id;
$order_item->quantity = $item->quantity;
$order_item->price = $product->GetPrice->price;
if(!$order_item->save()){
return response()->json([
'message' => 'Unable to place your order. Try again.'
], 500);
}
});
当我尝试执行此操作时,我在Undefined variable: order
行上收到此错误$order_item->order_id = $order->id;
。为什么我无法访问订单对象?
答案 0 :(得分:1)
您必须使用use
将变量传递给闭包。
$items = $items->map(function ($item, $key) use ($order) {
$product = Product::where('id', $item->product_id)->first();
$order_item = new Order_Item();
$order_item->order_id = $order->id;
$order_item->product_id = $item->product_id;
$order_item->quantity = $item->quantity;
$order_item->price = $product->GetPrice->price;
if(!$order_item->save()){
return response()->json([
'message' => 'Unable to place your order. Try again.'
], 500);
}
});