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();
        }
    }

  

原文地址:https://www.cnblogs.com/dongkang/p/11091284.html