Yii2.0 for update 行級鎖


當我們遇到存在高並發並且對於數據的准確性有要求的場景,需要了解和使用for update

 

需要注意的點:

1、InnoDB默認是行級別的鎖,當有明確指定的主鍵時候,是行級鎖。否則是表級別

2、for update 僅適用於InnoDB,並且必選開啟事務, 在begin與commit之間才生效

 

public function actionTest(){
        $db = Yii::$app->db;
        $transaction = $db->beginTransaction();
        try{
            $sql = "select * from ".User::tableName()." where user_id=5 for update";
            $userInfo = User::findBySql($sql)->one();
            $userInfo->nickname= 'asfasdfasfdaf';
            $userInfo->save();
            $transaction->commit();
            $this->success();
        }catch (ServiceException $e){
            $transaction->rollBack();
            $this->error();
        }
    }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM