注意事项

  • SQL updqte 语句是返回更新的行记录数,需要注册更新0条记录的情况
  • 库存,或数量等字段需要设置成无符号(unsigned)
  • Mysql 表存储引擎必须为innodb
  • 更新库存、或数量时,update语句需要加上where条件。
  • 事务必须是在同一个数据库连接中才能生效,thinkphp模型属性中如果配置了$connection就会导致这个问题

代码示例

Thinkphp6

Db::startTrans();
try {
// 业务一
$res = BusinesService::businessAction();
if (!$res) {
$msg = "业务一,失败!";
throw new Exception($msg);
}

// 业务二
$res = OrderService::businessAction();
if (!$res) {
$msg = "业务二,失败!";
throw new Exception($msg);
}

// 业务三
$res = CouponService::businessAction();
if (!$res) {
$msg = "业务三,失败!";
throw new Exception($msg);
}

// 业务n
$res = OtherService::businessAction();
if (!$res) {
$msg = "业务n,失败!";
throw new Exception($msg);
}

Db::commit();
return true;
} catch (HttpException $e) {
// 业务异常
Db::rollback();
fail($e);
} catch (Exception $e) {
Db::rollback();
abort(Result::$error_log, $e->getMessage());
}
return false;
}