且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何管理为多个用户同时添加购物车相同的产品?

更新时间:2023-09-10 17:21:28

你需要在查询中使用 TRANSACTION ,在数据库中插入订单详细信息。



添加到购物车时,如果时间相同,则无法确定是否有其他用户添加了它。在下订单时,您的查询将只允许一个交易,并且在完成之后它将处理另一个请求。



因此,当两个请求都将到达数据库时,一个人会先经历。然后,当第二个进入时,您应该在查询中检查以查看是否有剩余的产品数量。如果有任何剩余,则允许插入,否则不显示并向用户显示此时产品不可用的消息。
You need to use TRANSACTION in the query which inserts the order details in the database.

While adding to the cart, you cannot determine whether any other user has added it or not, if the time is same. While placing the order, your query will allow only one transaction and after the completion of that it will process another request.

So, when both request will hit the database, one will go through first. Then when second goes, you should have a check inside the query to see if there is any quantity left for the product or not. If there is any left, then allow insert, otherwise not and show message to user that the product is not available at this moment.