根据ACID一致性原则,事务对于要修改连续相关的多条数据,非常便于操作。如果执行过程中,任意一步不成功就回滚,保存原有数据。
在模型中需要引入:
use think\facade\Db;
在开始事务前创建事务,Db::startTrans() 执行使用 try 执行语句,成功则 Db::commit() ,若出现问题在catch结构 中执行Db::roollback()
Db::startTrans();
try(
//执行相关语句
Db::commit();
)catch(\Exception $e){
Db::rollback();
return null;
}
相关代码范例:(其中一个方法)
Db::startTrans();
try {
// 创建用户模型实例
$userModel = new UserModel();
// 创建订单模型实例
$orderModel = new OrderModel();
// 插入用户数据
$userModel->save(['name' => 'bbb', 'age' => 20]);
// 插入订单数据
$orderModel->save(['user_id' => $userModel->id, 'amount' => 100]);
// 提交事务
Db::commit();
} catch (\Exception $e) {
// 回滚事务
Db::rollback();
}
手动触发事务
使用throw new \Exception(‘插入第二条数据失败’); 触发事务,捕获错误的信息$e->getMessage()
Db::startTrans();
try {
// 插入第一条数据
$result1 = Db::table('table1')->insertGetId($data1);
if (!$result1) {
throw new \Exception('插入第一条数据失败');
}
// 插入第二条数据
$result2 = Db::table('table2')->insert($data2);
if (!$result2) {
throw new \Exception('插入第二条数据失败');
}
// 提交事务
Db::commit();
return ['status' => 'success', 'message' => '数据插入成功'];
} catch (\Exception $e) {
// 回滚事务
Db::rollback();
// 返回错误信息
return ['status' => 'error', 'message' => $e->getMessage()];
}
}