简体   繁体   English

如何在Laravel中从另一个表中减去一个表上的值

[英]How do you subtract a value on one table with a value from another table in laravel

I have two tables one called products and the other called orders. 我有两个表,一个称为产品,另一个称为订单。
Products as columns: id, plant_name, price, stock. 产品列:id,plant_name,price,stock。
Orders as columns: id product_id, quantity. 订单为列:编号product_id,数量。

When someone makes a order they pick a quantity. 当某人下订单时,他们会选择一个数量。 How do I reduce the quantity from the stock on the other table? 如何减少另一张桌子上的库存数量?

I am using controllers and elequent in Laravel if that helps. 我在Laravel中使用控制器和elequent,如果有帮助。

This seems like a general implementation question? 这似乎是一个一般的实现问题?

It depends on how you process orders. 这取决于您如何处理订单。 If new ones are stored in a table and you're running a cron that goes through them, then loop the orders and update quantity one by one. 如果新的存储在表中,并且您正在运行通过它们的cron,则循环订购并逐个更新数量。

Ex: 例如:

 $newOrders = \DB::table('orders')->get();
 foreach ($newOrders as $order){
     $stock = \DB::table('products')->where('id', $order->product_id)->first()->stock;
     if($stock > $order->quantity){
         \DB::table('products')->where('id', $order->product_id)->decrement('stock',$order->quantity);
 }

If you process it on the fly in the controller, then skip the loop above and simply update the products table when you process the order.. 如果您在控制器中即时处理它,则跳过上面的循环,在处理订单时只需更新产品表即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM