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语句时,没 ...
随机推荐
- 推荐一篇关于java 学习的文章,感觉写的很不错
---恢复内容开始--- 很多网友问我学习Java有没有什么捷径,我说"无他,唯手熟尔".但是我却很愿意将自己学习的一些经验写出来,以便后来者少走弯路,帮助别人是最大的快乐嘛 ...
- linux 卸载编译安装的软件
有些软件会有 make uninstall 之类的功能,但大多都没有,所以只有手动删除,或者在configure的时候加个preifx参数,比如 --preifx=/opt/squid,这样当你不用的 ...
- gvim 安装YCM
gvim的插件安装笔记 1.安装vunble插件 该插件主要用于管理别的插件,借助与git,从github来下载插件,实现自动安装前提条件是git安装正确,可以听过cnd使用,并且可以正确访问gith ...
- ecshop后台新功能权限的添加
1.在后台“推荐管理”里添加“推荐人分成”.“会员分成”两个操作功能以及权限 index.php?act=menu incluedes/inc_priv.php:权限对照表.inc_men ...
- 给div添加滚动条
最简单的方法: <div style="height:300px;width:100px;overflow:auto"><div/>(height和widt ...
- Ruby中实现module继承
module FooModule def self.included base base.extend ClassMethods end module ClassMethods def ...
- css_随笔
1 css 基础语法: 2 派生选择器 li strong { font-style: italic; font-weight: normal; } <p><strong>我是 ...
- Picard报错“MAPQ should be 0 for unmapped read”的解决方法
picard对bwa生成的sam文件进行reorder时,报错如下: Getting Help Exception in thread "main" htsjdk.samtools ...
- Linux远程执行Shell命令或脚本
## 远程执行shell命令 ssh [user]@[server] '[command]' # eg. ssh root@192.168.1.1 'uptime' ## 远程执行本地shell脚本 ...
- 【Network】OVS VXLAN/GRE 实践
参考资料: OVS/VXLAN/GRE参考 ovs vxlan IP overray_百度搜索 OVS操作总结-Neutron-about云开发 OpenStack OVS GRE/VXLAN网络_z ...