Laravel DB ::事务不会在异常上回滚 [英] Laravel DB::transaction not rolling back on exception

查看:732
本文介绍了Laravel DB ::事务不会在异常上回滚的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Laravel 4.2和DB :: transaction中遇到了一个小问题.我遇到了交易无法回滚的问题,因此我尝试了最简单的代码片段,并将其放入routes.php中以进行测试:

I'm having this small issue with Laravel 4.2 and DB::transaction. I was having an issue with transactions not being rolled back so I tried the easiest snippet of code and put it into routes.php for testing purposes:

routes.php:

routes.php:

DB::transaction(function(){

  $user = App::make("User");
  $user->save();
  throw new Exception("Should not create users");
});
...
...
... 
Some other code here 

简而言之,我尝试在事务关闭内创建用户,并在创建用户后抛出异常以强制回滚事务.我的问题是,即使抛出异常,事务也不会回滚.每次刷新应用程序时,我都会在数据库中获得新用户.相同的代码可以在本地计算机上正常工作,但是在我打算用于生产的服务器上,它根本不会回滚事务.你有什么想法吗?

Simply I try to create user within transaction closure and after user is created I throw exception to force rollback of transaction. My problem is that even thou exception is thrown, the transaction does not roll back. I'm getting new user in the database every time I refresh the app. The same code works as intended on the local machine, but on the server i'm planning to use for production it simply does not roll the transaction back. Do you have any ideas why ?

服务器MySql:5.1.73-cll-MySQL社区服务器(GPLv2)

Server MySql: 5.1.73-cll - MySQL Community Server (GPLv2)

服务器PHP:PHP 5.4.30(cli)(内置:2014年7月19日15:22:18)

Server PHP: PHP 5.4.30 (cli) (built: Jul 19 2014 15:22:18)

本地PHP:5.5.9

Local PHP: 5.5.9

本地MySql:5.6.16

Local MySql: 5.6.16

服务器安装在CentO上,而本地计算机是Windows7.

Server is sitting on CentOs while local machine is Windows 7.

推荐答案

因此,我正在回答自己的问题.直到MySql 5.5,InnoDb才是默认存储引擎.就我而言,MYISAM是默认存储引擎,不支持事务.我要做的是在我的CPanel服务器安装MySQL中启用InnoDB.比起我必须确保我的Laravel迁移中的每个表都是使用InnoDB引擎创建的.我通过添加以下内容来做到这一点:

So I'm responding to my own question. InnoDb was not a default storage engine until MySql 5.5. In my case MYISAM was the default storage engine and did not support the transactions. What I had to do is enable InnoDB in my CPanel server installation of MySQL. Than I had to make sure each of the tables in my Laravel migrations was created with InnoDB engine. I did that by adding:

     $table->engine = "InnoDB"; 

到每个迁移文件.一旦使用InnoDB引擎设置了所有表,事务就会按预期工作.

to each migration file. Once all the tables were set up with InnoDB engine, transactions work as intended.

这篇关于Laravel DB ::事务不会在异常上回滚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆