Laravel之路——事务


准备:

  表必须是InnoDB引擎

DB::beginTransaction();
try{
    $name = 'abc';
    $result1 = Test::create(['name'=>$name]);
    if (!$result1) {
        /**
         * Exception类接收的参数
         * $message = "", $code = 0, Exception $previous = null
         */
        throw new \Exception("1");
    }
    $result2 = Test::create(['name'=>$name]);
    if (!$result2) {
        throw new \Exception("2");
    }
    DB::commit();
} catch (\Exception $e){
    DB::rollback();//事务回滚
    echo $e->getMessage();
    echo $e->getCode();
}

  注意:如果id是自增的话,mysql的primary key是在内存中维护的,事务回滚是不会回退id,所以中间会出现断层


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM