併發情況下產品超賣

在併發時減庫存不能簡單地通過
update(['stock' => stock - $amount])來操作,在高併發的情況下會有問題。

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

這樣可以保證不會出現執行之後 stock 值爲負數的情況,也就避免了超賣的問題。根據返回的受影響行數來判斷是否執行成功。

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