Yii2 事务操作
官网关于Yii2 事务的说明文档
http://www.yiiframework.com/doc-2.0/guide-db-active-record.html
Working with Transactions
There are two ways of using transactions while working with Active Record.
The first way is to explicitly enclose Active Record method calls in a transactional block, like shown below,
$customer = Customer::findOne(123);
Customer::getDb()->transaction(function($db) use ($customer) {
$customer->id = 200;
$customer->save();
// ...other DB operations...
});
// or alternatively
$transaction = Customer::getDb()->beginTransaction();
try {
$customer->id = 200;
$customer->save();
// ...other DB operations...
$transaction->commit();
} catch(\Exception $e) {
$transaction->rollBack();
throw $e;
}
The second way is to list the DB operations that require transactional support in the yii\db\ActiveRecord::transactions() method. For example,
class Customer extends ActiveRecord
{
public function transactions()
{
return [
'admin' => self::OP_INSERT,
'api' => self::OP_INSERT | self::OP_UPDATE | self::OP_DELETE,
// the above is equivalent to the following:
// 'api' => self::OP_ALL,
];
}
}
The yii\db\ActiveRecord::transactions() method should return an array whose keys are scenario names and values are the corresponding operations that should be enclosed within transactions. You should use the following constants to refer to different DB operations:
- OP_INSERT: insertion operation performed by insert();
- OP_UPDATE: update operation performed by update();
- OP_DELETE: deletion operation performed by delete().
Use the | operators to concatenate the above constants to indicate multiple operations. You may also use the shortcut constant OP_ALL to refer to all three operations above.
Transactions that are created using this method will be started before calling beforeSave() and will be committed after afterSave() has run.
Yiifans的翻译(权威指南)文档
事务(Transaction)
你可以向下面这样执行一个数据库事务:
$transaction = $connection->beginTransaction();
try {
$connection->createCommand($sql1)->execute();
$connection->createCommand($sql2)->execute();
// ... 执行查询语句 ...
$transaction->commit();
} catch(Exception $e) {
$transaction->rollBack();
}
还可以嵌套事务:
// 外层事务
$transaction1 = $connection->beginTransaction();
try {
$connection->createCommand($sql1)->execute(); // 内层事务
$transaction2 = $connection->beginTransaction();
try {
$connection->createCommand($sql2)->execute();
$transaction2->commit();
} catch (Exception $e) {
$transaction2->rollBack();
} $transaction1->commit();
} catch (Exception $e) {
$transaction1->rollBack();
}
多个sql执行(不同的表ActiveRecord)任意一个无法成功提交都要能回滚, 但这样执行的时候依然插入成功而没有回滚
SysOrderFeedback正常save, SysOrderFeedbackServer中title必须为string
$transaction = Yii::$app->db->beginTransaction();
try {
$sysOrderFeeback = new \common\models\SysOrderFeedback();
$sysOrderFeeback->categ = 1;
$sysOrderFeeback->ltype = 1;
$sysOrderFeeback->create_time = 1;
$sysOrderFeeback->total = 1;
$sysOrderFeeback->open_remark = 1;
$sysOrderFeeback->save();
// ...other DB operations...
$sysOrderFeedbackServer = new \common\models\SysOrderFeedbackServer();
$sysOrderFeedbackServer->fid = 1;
$sysOrderFeedbackServer->title = 1;
$sysOrderFeedbackServer->create_time = 1;
$sysOrderFeedbackServer->save();
$transaction->commit();
} catch (\Exception $e) {
$transaction->rollBack();
throw $e;
}
打印:
print_r($sysOrderFeedbackServer->errors);
提示Array ( [title] => Array ( [0] => Title必须是一条字符串。 ) )
开启事务,只要没有commit()即使验证成功的save也保存不了,如下
$transaction = Yii::$app->db->beginTransaction();
$sysOrderFeeback = new \common\models\SysOrderFeedback();
$sysOrderFeeback->categ = 1;
$sysOrderFeeback->ltype = 1;
$sysOrderFeeback->create_time = 1;
$sysOrderFeeback->total = 1;
$sysOrderFeeback->open_remark = 1;
$sysOrderFeeback->save();
后来改成下下策判断Model->errors 暂时解决问题
$transaction = Yii::$app->db->beginTransaction();
$sysOrderFeeback = new \common\models\SysOrderFeedback();
$sysOrderFeeback->categ = 1;
$sysOrderFeeback->ltype = 1;
$sysOrderFeeback->create_time = 1;
$sysOrderFeeback->total = 1;
$sysOrderFeeback->open_remark = 1;
$sysOrderFeeback->save();
// ...other DB operations...
$sysOrderFeedbackServer = new \common\models\SysOrderFeedbackServer();
$sysOrderFeedbackServer->fid = 1;
$sysOrderFeedbackServer->title = 1;
$sysOrderFeedbackServer->create_time = 1;
$sysOrderFeedbackServer->save();
if (empty($sysOrderFeeback->errors) && empty($sysOrderFeedbackServer->errors)) {
$transaction->commit();
echo 'True';
} else {
$transaction->rollBack();
echo 'false';
}
跟踪Debug

关于更多的Yii2事务操作(事务级别、事务备份、事务有效性、多主从数据库事务)查看http://www.yiichina.com/doc/guide/2.0/db-dao
Yii2 事务操作的更多相关文章
- YII2中操作数据库的方式
一.以createCommand方式: // YII2中通过createCommand来处理数据库 // 查询多条记录 // {{%user}} 表示如果设置了表前缀,YII会自动帮你替换 $data ...
- [PHP] - PDO事务操作
PHP使用PDO事务操作数据库. 参考文章: http://php.ncong.com/mysql/pdo/pdo_shiwu.html 上代码: <!doctype html> < ...
- Winform开发框架里面使用事务操作的原理及介绍
在很多情况下,事务是个很有用的东西,可以把一系列的操作组合成一个原子粒度的操作,一旦组合中某个地方出错,可以整个干净的进行滚回,不会留下脏数据:除此之外,事务还能提高批量操作的效率,如在本地SQLit ...
- yii2 数据库操作(转)
开始使用数据库首先需要配置数据库连接组件,通过添加 db 组件到应用配置实现("基础的" Web 应用是 config/web.php),DSN( Data Source Name ...
- andorid SQLite数据库的增删改查 和事务操作
.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android ...
- Entity Framework 4 数据事务操作
利用数据库链接进行事务操作 var db = ConnectionHelper.GetConn(ConnectionType.Write);//获取上下文 var conn = db.Connecti ...
- 使用事务操作SQLite数据批量插入,提高数据批量写入速度,源码讲解
SQLite数据库作为一般单机版软件的数据库,是非常优秀的,我目前单机版的软件产品线基本上全部替换Access作为优选的数据库了,在开发过程中,有时候需要批量写入数据的情况,发现传统的插入数据模式非常 ...
- Oracle 数据库基本操作——实用手册、表操作、事务操作、序列
目录: 0. 参考链接与参考手册1. oracle 实用(常用操作)指令2. 数据库基本操作语法 a) 表操作 1)创建表 2)更新表 3)删除表 4)查询 b) 事务操作 c) 序列操作 1)创建序 ...
- Dapper事务操作
1.报错信息: 如果分配给命令的连接位于本地挂起事务中,ExecuteNonQuery 要求命令拥有事务.命令的 Transaction 属性尚未初始化. 出现这种原因是在执行Execute语句时,没 ...
随机推荐
- GIT文档
GIT文档http://git.oschina.net/progit/http://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c ...
- 关于点击Invalidate Caches/Restart禁止插件后,重新加载--Android Studio
1:47:27 Plugin Error Problems found loading plugins: Plugin "Google Analytics Uploader" wa ...
- 提升PHP编程效率的20个要素
用单引号代替双引号来包含字符串,这样做会更快一些.因为PHP会在双引号包围的字符串中搜寻变量,单引号则 不会,注意:只有echo能这么做,它是一种可以把多个字符串当作参数的“函数”(兄弟连PHP编程: ...
- mysql练习题-查询同时参加计算机和英语考试的学生的信息-遁地龙卷风
(-1)写在前面 文章参考http://blog.sina.com.cn/willcaty. 针对其中的一道练习题想出两种其他的答案,希望网友给出更多回答. (0) 基础数据 student表 +-- ...
- java开发人员,最应该学习和熟练使用的工具类。google guava.(谷歌 瓜娃)
学习参考文章: http://blog.csdn.net/wisgood/article/details/13297535 http://ifeve.com/google-guava/ http:// ...
- maven实战(02)_坐标详解
(一) 何为mave坐标 maven的世界中拥有数量非常巨大的构件,也就是平时用的一些jar,war等文件. maven定义了这样一组规则: 世界上任何一个构件都可以使用Maven坐标唯一标志,ma ...
- Mantis搭建步骤
(1)安装EeasyPHP (2)解压Mantis到EeasyPHP内www目录下 (3)将PHP复制到www目录下 并修改apache下httpd.conf及php.ini两个文件的php配置目录 ...
- TBitmapSurface.StretchFrom
procedure TBitmapSurface.StretchFrom(const Source: TBitmapSurface; const NewWidth, NewHeight: Intege ...
- python 输出大文本文件
输出固定函数 >>> with open(r'd:\test.txt','r') as f: for i , v in enumerate(f): if i>10: break ...
- erlang 虚机性能调优
erlang 默认启动参数更多的是针对电信平台实时特性,简单调整参数能很大程度降低CPU消耗,提高处理能力. 1. 关闭spin_wait 设置参数:+sbwt none 我上一篇文章提到:erlan ...