Laravel 数据库事务不起作用

Mat*_*Boy 7 php mysql laravel

我正在尝试在Laravel 5.5 中设置数据库事务但它似乎不起作用。我使用MySQL 5.7.20,工具模式中的所有表都是 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
    );
}
Run Code Online (Sandbox Code Playgroud)

并且它不会回滚事务。如果在某些删除或插入后发现异常,则不会还原它们。

起初我认为这可能是 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;
Run Code Online (Sandbox Code Playgroud)

它会回滚所有删除和所有插入(如预期的那样),tools.exercises_list_allocations表没有发生任何变化。所以,我排除了数据库服务器的问题。

所以,我认为它应该与 PHP 代码有关。我在网上搜索了与我类似的问题,并尝试了一些报告的解决方案。

我尝试使用带有匿名函数而不是 try/catch 块的 DB::transaction() 方法,但没有成功。

我尝试使用 Eloquent ORM 而不是 DB::insert() 和 DB::delete() 方法,两者都尝试使用带有匿名函数的 DB::transaction() 方法和 DB::beginTransaction(), DB:: commit() 和 DB::rollBack() 方法,没有成功。

我尝试禁用严格模式并强制引擎成为 config/database.php 中的 InnoDB,但没有成功。

我究竟做错了什么?我需要在单个原子事务中运行所有删除和插入。

Mat*_*Boy 13

如果您和我一样,在您的应用程序中配置了多个数据库连接,您必须在调用事务方法之前选择一个连接,如 ThejakaMaldeniya 的评论所建议的,如果您要运行的查询不在默认连接中:

DB::connection('tools')->beginTransaction();
DB::connection('tools')->commit();
DB::connection('tools')->rollBack();
Run Code Online (Sandbox Code Playgroud)

它完美地工作。