事务方法
MySQL 事务通常围绕以下三个方法配合使用:
php
beginTransaction() // 开始
commit() // 提交
rollBack() // 回滚使用示例
下面的示例演示了“创建订单并扣减库存”的典型事务场景:只要有任一步骤失败,就会回滚,确保数据一致性。
php
$model = m('order');
$model->beginTransaction();
try {
$data = array(
'user_id' => 'demo',
'price' => 150.00,
);
// 添加订单
$id = $model->insert($data);
if (!$id) {
throw new \Exception('add order err');
}
// 扣减库存
$re = m('goods')->where(array('goods_id' => 1))->setDec('num', 1);
if (!$re) {
throw new \Exception('update goods num err');
}
// 提交
$model->commit();
} catch (\Exception $e) {
// 回滚
$model->rollBack();
$msg = $e->getMessage();
ajax(-1, $msg); // 返回错误信息
}适用场景
凡是多个写操作必须同时成功或同时失败的业务,都应该使用事务,例如下单、扣库存、余额变更或批量状态更新。