我是一名有用的助手,可以为您翻译文本。
我正在尝试在Laravel 5.5中设置数据库事务,但似乎无法正常工作。我使用MySQL 5.7.20,并且所有来自tools模式的表都是InnoDB。我还运行PHP 7.2.3。
我有以下代码:
而且它回滚了所有的删除和插入操作(正如预期的那样),tools.exercises_list_allocations表中没有发生任何更改,因此我排除了数据库服务器是问题的原因。
因此,我认为应该是PHP代码有问题。我在网上搜索了与我的问题类似的问题,并尝试了一些报告的解决方案。
我尝试使用DB :: transaction()方法来代替try/catch块中的匿名函数,但没有成功。
我尝试使用Eloquent ORM而不是DB::insert()和DB::delete()方法,同时尝试了DB::transaction()方法与匿名函数以及DB::beginTransaction(),DB::commit()和DB::rollback()方法,但都没有成功。
我尝试禁用严格模式并在config/database.php中强制将引擎设置为InnoDB,但也没有成功。
我做错了什么?我需要所有的删除和插入操作在一个原子事务中运行。
我正在尝试在Laravel 5.5中设置数据库事务,但似乎无法正常工作。我使用MySQL 5.7.20,并且所有来自tools模式的表都是InnoDB。我还运行PHP 7.2.3。
我有以下代码:
DB::beginTransaction();
try {
// checks whether the users marked for removal are already assigned to the list
foreach ($removeStudents as $removeStudent) {
if ($ls->allocatedStudents->find($removeStudent->id) === null) {
throw new Exception('userNotAllocated', $removeStudent->id);
} else {
DB::connection('tools')->table('exercises_list_allocations')
->where('user_id', $removeStudent->id)
->where('exercises_list_id', $ls->id)
->delete();
}
}
// checks whether the users marked for removal are already assigned to the list
foreach ($addStudents as $addStudent) {
if ($ls->allocatedStudents->find($addStudent->id) === null) {
DB::connection('tools')->table('exercises_list_allocations')
->insert([
'user_id' => $addStudent->id,
'exercises_list_id' => $ls->id
]);
} else {
throw new Exception('userAlreadyAllocated', $addStudent->id);
}
}
DB::commit();
} catch (Exception $e) {
DB::rollBack();
return response()->json(
[
'error' => $e->getMessage(),
'user_id' => $e->getCode()
], 400
);
}
它不会回滚事务。如果在一些删除或插入操作之后发现异常,则不会恢复它们。
起初我以为这可能是MySQL的问题,所以我尝试手动运行以下SQL查询:
START TRANSACTION;
DELETE FROM tools.exercises_list_allocations WHERE user_id = 67 AND exercises_list_id=308;
DELETE FROM tools.exercises_list_allocations WHERE user_id = 11479 AND exercises_list_id=308;
INSERT INTO tools.exercises_list_allocations (user_id, exercises_list_id) VALUES (1,308);
INSERT INTO tools.exercises_list_allocations (user_id, exercises_list_id) VALUES (2,308);
INSERT INTO tools.exercises_list_allocations (user_id, exercises_list_id) VALUES (3,308);
ROLLBACK;
而且它回滚了所有的删除和插入操作(正如预期的那样),tools.exercises_list_allocations表中没有发生任何更改,因此我排除了数据库服务器是问题的原因。
因此,我认为应该是PHP代码有问题。我在网上搜索了与我的问题类似的问题,并尝试了一些报告的解决方案。
我尝试使用DB :: transaction()方法来代替try/catch块中的匿名函数,但没有成功。
我尝试使用Eloquent ORM而不是DB::insert()和DB::delete()方法,同时尝试了DB::transaction()方法与匿名函数以及DB::beginTransaction(),DB::commit()和DB::rollback()方法,但都没有成功。
我尝试禁用严格模式并在config/database.php中强制将引擎设置为InnoDB,但也没有成功。
我做错了什么?我需要所有的删除和插入操作在一个原子事务中运行。
DB::transaction()
将你的代码包装在一个事务闭包中?Laravel 将会为你处理commit
和rollback
,无论你在何处退出闭包。这种方式可以将必须作为事务运行的代码隔离起来 - 当你离开这个隔离区域时,事务将被保证要么提交要么回滚。 - Jason