在2种模型中使用try catch时,如何解决laravel中的回滚事务?

时间:2019-07-18 11:50:06

标签: laravel-5 eloquent try-catch rollback

当我在模型中使用try catch时,我的回滚事务在控制器中不起作用吗?

在我的代码中

try{
    DB::begin Transaction();

    $array = array("0" => "1", "1" => "2");
    for each($array as $data){
        $data = new Test();
        $save = $data->test();

        $data = new Second();
        $save = $data->test();
    }

    DB::commit();
}catch($e){
    DB::rollback();
}

在我班上

public function test(){
    try{
        $log = new Test;
        $log->id = '20';
        $log->text = '30';
        $log->save();
    } catch (\Exception $e) {

    }
}


public function second(){
    try{
        $log = new Second;
        $log->ids = '40';
        $log->text = '50';
        $log->save();
    } catch (\Exception $e) {

    }
}

如何使代码回滚?

1 个答案:

答案 0 :(得分:0)

我相信您的test()second()函数中发生了异常,并且您有一个try-catch,它不会让异常进入主函数。从test()second()函数中删除try-catch,它应该可以正常工作。

public function test(){
    $log = new Test;
    $log->id = '20';
    $log->text = '30';
    $log->save();
}

public function second(){
    $log = new Second;
    $log->ids = '40';
    $log->text = '50';
    $log->save();
}