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
{

}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM