tp6在操作數據庫時,如果出現錯誤會直接拋出異常,單表操作時可以隨便搞了。在多表操作時,如果后面的表出現異常會導致數據混亂,慘不忍睹。怎么解決呢?
當然是啟用事務日志,在異常時回滾事務,注意MySQL 的 MyISAM 不支持事務處理,需要使用 InnoDB 引擎。
// 啟動事務 Db::startTrans(); try { //表一保存 $user->money = $user->money-$proem['money']; $user->save(); // 表二保存 $where['user_bank_id'] = $proem['bankid']; $where['money'] = $proem['money']; $where['user_id'] = $this->uid; $where['create_time'] = time(); (new UserRawal)->save($where); // 提交事務 Db::commit(); return $this->success(); } catch (\Exception $e) { // 回滾事務 Db::rollback(); return $this->error($e->getMessage()); } return $this->error("錯誤");
注意引入Db類
use think\facade\Db;
使用以上方法就可以避免數據混亂啦,點擊查看更多tinkphp技巧。