$model->startTrans(); // 开启事务
$model->rollback(); // 事务回滚
$model->commit(); // 提交事务
<?php
/**
* 事务测试
*/
public function transaction()
{
$modelA = model('A');
$modelA->startTrans(); // 开启事务A
$result = $modelA->save($data1);
if($result === false){
$modelA->rollBack(); // 事务A回滚
$this->error('添加A信息失败,请重试');
}
$modelB = model('B');
$modelB->startTrans(); // 开启事务B
$result = $modelB->save($data2);
if($result === false){
$modelB->rollBack(); // 事务B回滚
$modelA->rollBack(); // 事务A回滚
$this->error('添加B信息失败,请重试');
}
$modelC = model('C');
$modelC->startTrans(); // 开启事务C
$result = $modelC->save($data3);
if($result === false){
$modelC->rollBack(); // 事务C回滚
$modelB->rollBack(); // 事务B回滚
$modelA->rollBack(); // 事务A回滚
$this->error('添加C信息失败,请重试');
}
// 提交事务
$modelC->commit();
$modelB->commit();
$modelA->commit();
$this->success('添加成功', url('admin/index/add'));
}