我正在尝试在 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 block 一起使用,但没有成功。
我尝试使用 Eloquent ORM 而不是 DB::insert() 和 DB::delete() 方法,这两个方法都尝试了带有匿名函数的 DB::transaction() 方法和 DB::beginTransaction(), DB::commit() 和 DB::rollBack() 方法,没有成功。
我尝试在 config/database.php 中禁用严格模式并强制引擎为 InnoDB,但没有成功。
我做错了什么?我需要在单个原子事务中运行所有删除和插入操作。
最佳答案
如果您和我一样,在您的应用程序中配置了多个数据库连接,您必须在调用事务方法之前选择一个连接,如 ThejakaMaldeniya 的评论所建议的那样,如果您要运行的查询不在默认连接中:
DB::connection('tools')->beginTransaction();
DB::connection('tools')->commit();
DB::connection('tools')->rollBack();
而且效果很好。
关于php - Laravel 数据库事务不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50720341/