官网关于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. 配置LVS + Keepalived高可用负载均衡集群之图文教程

    负载均衡系统可以选用LVS方案,而为避免Director Server单点故障引起系统崩溃,我们可以选用LVS+Keepalived组合保证高可用性.  重点:每个节点时间都同步哈! C++代码 [r ...

  2. OOP,WEB开发实用小技巧

    偶然读到一篇博客,记录一下心得.这种设计对于新手来说一般是想不到的,它充分的发挥了OOP语言的特性,让代码专用而清爽.这是不是重构的思想呢? 我们在写业务层的时候,有很多方法是重复功能的,我们就可以使 ...

  3. 页面测试点testpoint

    页面测试点整理(非逻辑测试点) 由于自己一年来一直在做页面测试,也看了很多测试理论的书和方法,但是方法并非也无法照搬,此处总结自己工作以来通过各种坑摸出来的一些方法点,希望一边靠上经典测试理论,一边形 ...

  4. springmvc @responsebody 406/415问题解决

    提供几个解决思路 1.如果项目中用的spring jar包是4.x版本, 需要jackson-annotations-2.x/jackson-core-2.x/jackson-databind-2.x ...

  5. jQuery的选择器中的通配符[id^='code'] 等示例及说明

    1.选择器 (1)通配符: $("input[id^='code']");//id属性以code开始的所有input标签 $("input[id$='code']&quo ...

  6. JAVA将数字字符串强制转换成整型变量----求参数之和实验代码(附流程图)

    一.设计思想 先将参数个数输出,并利用循环结果将参数逐个输出,再将字符串强制转化成整型,利用循环结构相加求和 二.程序流程图 三.源程序代码 package demo; public class Co ...

  7. linux 复 带进度条

    rsync命令 #rsync -av --progress /mnt/yidong2/full20100526.tar.gz /mnt/yidong1/ 可以实现本机带进度条提示拷贝,可以实现不同机器 ...

  8. python模块引用问题(比较杂乱,懒得整理)

    1 在stackoverflows摘抄 If the import module in the same dir, use e.g: from . import core If the import ...

  9. protocol http not supported or disabled in libcurl apt-get

    ubuntu 14.04 碰到了这个莫名其妙的问题.谷歌了一把,解决方案如下:http://askubuntu.com/questions/683857/curl-1-protocol-https-n ...

  10. 手写一个allocator

    似乎就像是一个计算机原理的实践.. 首先介绍一下大多数操作系统的内存架构..对于某个程序它会认为自己是独占了整个系统的所有内存在运行的这样才能方便移植,因此人们搞出了虚拟内存和物理内存的区别,于是人们 ...