订单对象未在集合的地图功能中定义

时间:2017-02-28 09:37:49

标签: laravel

我有两张表来下订单。在我的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;。为什么我无法访问订单对象?

1 个答案:

答案 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);
    }
});