这两天一直再纳闷,明明建立了事务,为什么 throw new Exception 之后事务一直都没有效!
一开始以为是 throw new Exception 的问题,百度查了一些资料说使用 RuntimeException ,试了之后还是不行!
再去检查数据库引擎是不是innodb,确认了几次,都发现没错!可是事务愣是没效果。。。
换种方式百度一下:tp5多表事务发现,人家全是用模型。然后自己再试了一下,终于可以了。。。
错误方法:
$data = [
'name' => "123",
'value' => "1",
];
$data1 = [
'name' => "234",
'value' => "23",
];
$data2 = [
'name' => "456",
'value' => "4",
];
db()->startTrans();
try{
$res = db("Test")->insertGetId($data);
$res1 = db("Test1")->insertGetId($data1);
$res2 = db("Test")->insertGetId($data2);
if($res2){
throw new Exception("1");
}
db()->commit();
}catch (Exception $e){
db()->rollback();
echo $e->getLine().$e->getMessage();
}
正确方法(一定要先建模型,空的模型也可以):
$data = [
'name' => "123",
'value' => "1",
];
$data1 = [
'name' => "234",
'value' => "23",
];
$data2 = [
'name' => "456",
'value' => "4",
];
Db::startTrans();
try{
$res = model("Test")->insertGetId($data);
$res1 = model("Test1")->insertGetId($data1);
$res2 = model("Test")->insertGetId($data2);
if($res2){
throw new Exception("1");
}
Db::commit();
}catch (Exception $e){
Db::rollback();
return $this->getReturnResult($e->getLine().$e->getMessage(),500);
}
附上两个模型:
<?php
namespace appapimodel;
use thinkModel;
class Test1 extends Model
{
}
<?php
namespace appapimodel;
use thinkModel;
class Test extends Model
{
}