>[success] 先引入命名空间 `use sys\Pdo;`
## 手动事务
~~~
Pdo::beginTransaction();
try {
Pdo::execute(
'UPDATE `users` SET credits = credits - :number WHERE uid = :uid',
[
'uid' => $uid,
'number' => $number,
]
);
Pdo::execute(
'INSERT INTO `credits`(`uid`, `number`) VALUES(:uid, :number)',
[
'uid' => $uid,
'number' => -$number,
]
);
// 提交事务
Pdo::commit();
} catch (\Exception $e) {
// 回滚事务
Pdo::rollBack();
throw $e;
}
~~~
## 自动事务 (推荐)
>[info] Pdo::transaction 方法的第二个参数为:是否调试,为 true 时如果SQL执行出错会抛出错误,为 false 时不抛出错误。
~~~
public function minusCredits($uid, $number)
{
// 变量转数组
$data = compact('uid', 'number');
// 执行事务
Pdo::transaction(function () use ($data) {
Pdo::execute(
'UPDATE `users` SET credits = credits - :number WHERE uid = :uid',
[
'uid' => $data['uid'],
'number' => $data['number'],
]
);
Pdo::execute(
'INSERT INTO `credits`(`uid`, `number`) VALUES(:uid, :number)',
[
'uid' => $data['uid'],
'number' => -$data['number'],
]
);
}, true);
}
~~~
## 回滚含有零影响行数的事务
`pdo.transaction.rollback_zero_affected` 配置项为 `true` 时,事务内的任意一条 `SQL` 如果返回的影响行数为零,本次事务将回滚。