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语句时,没 ...
随机推荐
- JKS和PKCS#12
今天来点实际工作中的硬通货! 与计费系统打交道,少不了用到加密/解密实现.为了安全起见,通过非对称加密交换对称加密密钥更是不可或缺.那么需要通过什么载体传递非对称算法公钥/私钥信息?数字证书是公钥的载 ...
- java 学习框架
例如 Jsp.Velocity.Tiles.iText 和 POI.Spring MVC框架并不知道使用的视图,所以不会强迫您只使用 JSP 技术.
- File 类
File 类:文件和目录(文件夹)路径名的抽象表现形式. 方法 1.创建功能 public boolean createNewFile():创建文件 public boolean mkdir():创建 ...
- coreseek 安装及使用方法详解
coreseek 安装及使用 一般站点都需要搜索功能,如果是php+mysql站点,建议选择coreseek,如果是java站点建议使用lucene,coreseek 是一款很好的中文全文检索/搜索软 ...
- 利用JS判断是否手机或pad访问
<script type="text/javascript"> /* * 智能机浏览器版本信息: * */ var browser={ versions:functio ...
- Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80070005 拒绝访问。
这几天在写一个导出word的功能,使用 Microsoft.Vbe.Interop.dll和Office.dll 在本地都可以正常运行,但是上传到服务器后就报错,如下图: 对于此问题,也在网上查了一些 ...
- phpstorm常用功能&快捷键(mac)
command + delete 删除整行 option + comman +enter 下面增加一行 command + D 复制出一行 command + / 单行注释 control + shi ...
- Java国际化(i18n)
Java国际化(i18n) 最近在做一个网站国际化的功能.用Java做开发,使用spring+velocity. Java提供了对i18n的支持,spring对其做了集成,可以很方便的配置.主要思想就 ...
- Max double slice sum 的解法
1. 上题目: Task description A non-empty zero-indexed array A consisting of N integers is given. A tripl ...
- STL
STL qsort intcompare(constvoid*arg1,constvoid*arg2){ return(*(int*)arg1<*(int*)arg2)?-1: (*(int*) ...