每当我有多个插入/更新查询时,我都会尝试一些新的东西。我为此使用数据库事务。
$this->transaction->beginTransaction();
try {
$trucker_user->update([
'username' => $request->getParam('username'),
'first_name' => $request->getParam('first_name'),
'middle_name' => $request->getParam('middle_name'),
'last_name' => $request->getParam('last_name'),
'contact_number' => $request->getParam('contact_number'),
'email' => $request->getParam('email'),
'status' => ($trucker_id) ? 1 : $request->getParam('status')
]);
if ($trucker_id === false) {
$trucker_user->userTrucker()->update([
'trucker_id' => $request->getParam('trucker_id')
]);
}
$this->transaction->commit();
} catch(\Exception $e) {
$this->transaction->rollBack();
throw $e;
}
所以问题是,当我有多个插入/更新查询时,我应该使用数据库事务,这是一个好的做法吗?
我知道当发生不好的事情时进行事务回滚是个好主意。但是每当我在多个查询中总是使用它是不是有点矫枉过正?
最佳答案
事务是为了保证一致性而设计的工具。如果第一个更新/插入操作在第二个失败时需要回滚,则需要事务。
在您的示例中,您更新了 trucker_user
的字段,然后在某些情况下,您还更新了其 id
。您应该向自己提出的问题是“如果 id
更新失败,我是否要回滚所有 trucker_user
更新?”
答案可能是肯定的,因为您必须保持两个操作之间的一致性,或者因为万一第二个操作失败,您必须重试,并且再次执行所有操作比查找过程中断的位置更容易(这样您就可以从那里开始)。
关于mysql - 多个查询上的数据库事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43634628/