结帐后减少数据库中的产品数量

Decrease product quantity in database after checkout

我的网上商店有购物车,到目前为止一切正常,但我说当我尝试将产品数量减少到产品时,我数据库中的所有产品都会减少,而不仅仅是购物车中的产品。

这是我的订单控制器:

public function postOrder(Request $request) {    
    $validator = Validator::make($request->all(), [
        'first_name' => 'required|max:30|min:2',
        'last_name'  => 'required|max:30|min:2',
        'address'    => 'required|max:50|min:4',
        'address_2'  => 'max:50|min:4',
        'city'       => 'required|max:50|min:3',
        'state'      => 'required|',
        'zip'        => 'required|max:11|min:4',
        'full_name'  => 'required|max:30|min:2',
    ]);

    if ($validator->fails()) {
        return redirect('/checkout')
            ->withErrors($validator)
            ->withInput();
    }

    $first_name = Input::get('first_name');
    $last_name = Input::get('last_name');
    $address = Input::get('address');
    $address_2 = Input::get('address_2');
    $city = Input::get('city');
    $state = Input::get('state');
    $zip = Input::get('zip');
    $full_name = Input::get('full_name');        
    $user_id = Auth::user()->id;
    $cart_products = Cart::with('products')->where('user_id', '=', $user_id)->get();
    $cart_total = Cart::with('products')->where('user_id', '=', $user_id)->sum('total')        
    $charge_amount = number_format($cart_total, 2) * 100;        
    $order = Order::create (
        array(
            'user_id'    => $user_id,
            'first_name' => $first_name,
            'last_name'  => $last_name,
            'address'    => $address,
            'address_2'  => $address_2,
            'city'       => $city,
            'state'      => $state,
            'zip'        => $zip,
            'total'      => $cart_total,
            'full_name'  => $full_name,
        ));

    foreach ($cart_products as $order_products) {
        $order->orderItems()->attach($order_products->product_id, array(
            'qty'    => $order_products->qty,
            'price'  => $order_products->products->price,
            'reduced_price'  => $order_products->products->reduced_price,
            'total'  => $order_products->products->price * $order_products->qty,
            'total_reduced'  => $order_products->products->reduced_price * $order_products->qty,
        ));
    }

// in the fact all product will decrement Not just products in cart
    \DB::table('products')->decrement('product_qty', $order_products->qty);

    Cart::where('user_id', '=', $user_id)->delete();

    flash()->success('Success', 'Your order was processed successfully.');

    return redirect()->route('cart');

}

我使用程序 \DB::table('products')->decrement('product_qty', $order_products->qty);; 进行减量,但实际上所有产品都会减量 不仅仅是购物车中的产品

您正在使用的 decrement 会更新所有记录,正如您观察到的那样,因为您没有将其限制为特定记录。您想在循环中执行此操作:

DB::table('products')
            ->where('id', '=', $order_products->product_id)
            ->decrement('product_qty', $order_products->qty);