减少库存管理中的产品数量



我希望它在下单后减少购物车中的库存产品数量。示例:具有5个ID的产品库存为50件,如果从该产品收到5个订单,我希望它更新为50-5=45。
注意:数字=当前订单中的产品数量

更详细的:cart_product表中有数字,products表中有库存,cart_products中的产品数量,从cart_production表中取数字,从product表的库存中减去,但我没有成功,你能帮我吗?

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();

// 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;
);
}

我不能使用列名,因为我不知道。请记住,您需要更改代码中的以下文本:

  • AAAAA=>"购买项目金额"中的列名;cart_ product";表
  • CCD_ 2=>商品库存的列名;产品";表

有关increment and decrement方法的更多信息,您可以查看https://laravel.com/docs/9.x/queries#increment-并递减

它的工作原理与类似

// 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
);}

最新更新