tp5.1 模型中使用事务

2020-08-06

方法1:

<?php
//伪代码
use think\Model;

class Student extends Model
{
    public function save_data()
    {
        $db = $this->db(false);
        $db->startTrans();
        try {
            $this::create(['data'=>1]);
            (new Score())->save(['data'=>2]);
            $db->commit();
        } catch (\Exception $e) {
            $db->rollback();
        }
    }
}

当在模型中使用另外一个模型时,事务回滚也是生效的;方法来源于:源码\think\Model.php中

方法2:

<?php
//伪代码
use think\Model;

class Student extends Model
{
    public function save_data()
    {
        $this->startTrans();
        try {
            $this::create(['data'=>1]);
            (new Score())->save(['data'=>2]);
            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
        }
    }
}

 

{/if}