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技巧。