TP5 多个表使用事务,千万不要用助手方法,不然你想哭

这两天一直再纳闷,明明建立了事务,为什么 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 app\api\model;

use think\Model;

class Test1 extends Model
{

}

  

<?php

namespace app\api\model;

use think\Model;

class Test extends Model
{

}

  

转载于:https://www.cnblogs.com/zwb121/p/11587229.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值