官网关于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:

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 事务操作的更多相关文章

  1. YII2中操作数据库的方式

    一.以createCommand方式: // YII2中通过createCommand来处理数据库 // 查询多条记录 // {{%user}} 表示如果设置了表前缀,YII会自动帮你替换 $data ...

  2. [PHP] - PDO事务操作

    PHP使用PDO事务操作数据库. 参考文章: http://php.ncong.com/mysql/pdo/pdo_shiwu.html 上代码: <!doctype html> < ...

  3. Winform开发框架里面使用事务操作的原理及介绍

    在很多情况下,事务是个很有用的东西,可以把一系列的操作组合成一个原子粒度的操作,一旦组合中某个地方出错,可以整个干净的进行滚回,不会留下脏数据:除此之外,事务还能提高批量操作的效率,如在本地SQLit ...

  4. yii2 数据库操作(转)

    开始使用数据库首先需要配置数据库连接组件,通过添加 db 组件到应用配置实现("基础的" Web 应用是 config/web.php),DSN( Data Source Name ...

  5. andorid SQLite数据库的增删改查 和事务操作

    .xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android ...

  6. Entity Framework 4 数据事务操作

    利用数据库链接进行事务操作 var db = ConnectionHelper.GetConn(ConnectionType.Write);//获取上下文 var conn = db.Connecti ...

  7. 使用事务操作SQLite数据批量插入,提高数据批量写入速度,源码讲解

    SQLite数据库作为一般单机版软件的数据库,是非常优秀的,我目前单机版的软件产品线基本上全部替换Access作为优选的数据库了,在开发过程中,有时候需要批量写入数据的情况,发现传统的插入数据模式非常 ...

  8. Oracle 数据库基本操作——实用手册、表操作、事务操作、序列

    目录: 0. 参考链接与参考手册1. oracle 实用(常用操作)指令2. 数据库基本操作语法 a) 表操作 1)创建表 2)更新表 3)删除表 4)查询 b) 事务操作 c) 序列操作 1)创建序 ...

  9. Dapper事务操作

    1.报错信息: 如果分配给命令的连接位于本地挂起事务中,ExecuteNonQuery 要求命令拥有事务.命令的 Transaction 属性尚未初始化. 出现这种原因是在执行Execute语句时,没 ...

随机推荐

  1. linux下libevent安装

    wget http://monkey.org/~provos/libevent-1.4.13-stable.tar.gz tar –xzvf libevent-1.4.13-stable.tar.gz ...

  2. redis 操作 hash 的测试

    1>hset setname field value hset stuSet name zhangsan:1        2>hget setname field hget stuset ...

  3. todo

     ID生成器要做成兼容分布式, 数据库ef控制要改成手动升级, 异常日志模块,操作日志某快,,, 日志服务器,, 图片服务器,,,动静分离, 前后台分离,, 可扩展性,无状态化集群弹性部署, 数据库主 ...

  4. AVL树

    AVL树 在二叉查找树(BST)中,频繁的插入操作可能会让树的性能发生退化,因此,需要加入一些平衡操作,使树的高度达到理想的O(logn),这就是AVL树出现的背景.注意,AVL树的起名来源于两个发明 ...

  5. ebay api接口开发基本步骤

    因公司项目需求,要进行ebay api开发,网上很多资料已过时,自己记录一下. 准备工作 一.注册账号 1开发者账号注册 https://developer.ebay.com/signin?retur ...

  6. 百度编辑器ueditor插入表格没有边框颜色的解决方法

    附:从word excel 中 复制的表格提交后无边框,参考这个同学的,写的很详细:   http://blog.csdn.net/lovelyelfpop/article/details/51678 ...

  7. JAVA WEB WITH IDEA

    本文主要介绍使用IDEA开发环境,创建JAVA WEB 工程,并介绍war包的制作过程. 1 创建MAVEN工程

  8. jcFeather Maya 羽毛插件

    jcFeather 2.8.6 插件持续更新地址为:http://www.jerrykon.com/jcFeather.html 和 http://www.creativecrash.com/maya ...

  9. qt5中文代码编码编译问题

    qt中文代码用vs2010编译问题解决 总结说就是qt5默认UTF8不支持微软默认的ANSI(GB2312/GBK).解决办法是把中文字符串全部用 QString::fromLocal8Bit() 封 ...

  10. nginx使用ngx_lua访问后端Thrift-Server实现和介绍

    背景 随着openresty的出现,让nginx使用lua解决一些业务的能力大幅度提高,ngx_lua可以使用nginx自生的基于事件驱动的IO模型,和后端的存储,业务等系统实现非阻塞的连接交互. 如 ...