并发情况下产品超卖

在并发时减库存不能简单地通过
update(['stock' => stock - $amount])来操作,在高并发的情况下会有问题。

$amount  = $data['amount '];
update product set stock = stock - $amount where id = $id and stock >= $amount

这样可以保证不会出现执行之后 stock 值为负数的情况,也就避免了超卖的问题。根据返回的受影响行数来判断是否执行成功。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章