Laravel数据库事务不起作用

时间:2018-06-06 12:24:56

标签: 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
    );
}

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

起初我认为它可能是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()方法都没有成功。

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

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

1 个答案:

答案 0 :(得分:3)

如果您(就我自己)在您的应用中配置了多个数据库连接,则必须在调用交易方法之前选择一个连接,如ThejakaMaldeniya的评论所建议的那样,如果您要运行的查询不是' t在默认连接中:

DB::connection('tools')->beginTransaction();
DB::connection('tools')->commit();
DB::connection('tools')->rollBack();

它完美无缺。