背景:yii2事务的应用,需要配置事务的同事,还需要手动开启事务才能有效,但一些逻辑谨慎的平台需要默认开启事务。不手动执行commit就不能执行,这就需要手动更改动yii2框架代码了。
//开启事务
$transaction = Yii::$app->getDb()->beginTransaction(); //如果注释掉整个事务,依旧可以执行
$user = TdUser::findOne(62);
$user->save();
$transaction->commit(); //如果注释掉整个事务,依旧可以执行
更新文件:**/db/Connection.php ,大概在715行,手动添加一段代码。
public function createCommand($sql = null, $params = [])
{
//默认全局启动事务 private edit
$transaction = $this->getTransaction();
if(!$transaction){
$transaction = $this->beginTransaction();
}
//end private edit
$driver = $this->getDriverName();
$config = ['class' => 'yii\db\Command'];
if ($this->commandClass !== $config['class']) {
$config['class'] = $this->commandClass;
} elseif (isset($this->commandMap[$driver])) {
$config = !is_array($this->commandMap[$driver]) ? ['class' => $this->commandMap[$driver]] : $this->commandMap[$driver];
}
$config['db'] = $this;
$config['sql'] = $sql;
/** @var Command $command */
$command = Yii::createObject($config);
return $command->bindValues($params);
}