Home > Net >  Reducing the number of products in stock management
Reducing the number of products in stock management

Time:10-09

I want it to reduce the number of products in the cart from stock after the order is placed. sample: The product stock with 5 IDs is 50 pieces, if 5 orders are received from this product,I want it updated to be 50 - 5 = 45.
note:number=the quantity of the product in the current order

more detailed: There is number in the cart_product table, stock in the products table,Number of products in cart_product,Taking the number from the cart_product table and subtracting it from the stock in the product table, but i didn't succeed can you help me please

DB::table('products')
->join('products', 'products.id', 'cart_product.product_id')
->join('cart_product', 'cart.id', 'cart_product.main_cart_id')
->where(session('active_cart_id'),'=','cart_product.main_cart_id')
->orWhere('cart_product.product_id','=','products.id')
->update();

CodePudding user response:


// Fetch items in the cart
$cartItems = DB::table('cart_product')
    ->where('main_cart_id', session('active_cart_id'))
    ->get();

foreach ($cartItems as $cartItem) {

    // Update stocks in the "products" table 
    DB::table('products')
        ->where('id',$cartItem->product_id)
        ->decrement(
            'AAAAA',
            $cartItem->BBBBB;
        );

}

I couldn't use the column names since I don't know. Keep in mind that you need to change the following texts in the code:

  • AAAAA => Column name of the purchased item amount in "cart_product" table.
  • $cartItem->BBBBB => Column name of item stock in "products" table.

For more information about increment and decrement methods, you can look at https://laravel.com/docs/9.x/queries#increment-and-decrement

CodePudding user response:

it worked like this

// Fetch items in the cart
        $cartItems = DB::table('cart_product')
            ->where('main_cart_id', session('active_cart_id'))
            ->get();
        foreach ($cartItems as $cartItem) {
            // Update stocks in the "products" table
            DB::table('products')
                ->where('id',$cartItem->product_id)
                ->decrement(
                'stock',
                $cartItem->number
        );}
  • Related