在事务中调度数据库更新作业 - 回滚查询

问题描述 投票:0回答:1

我有一个关于在事务中调度更新数据库的作业的问题。如果这些作业中的任何一个遇到错误,数据库会自动回滚到之前的状态吗?

这是我的代码:

DB::transaction(
    function () use ($allowance, $currentAllowanceHistory, $newStartAt, $currentStartAt, $updateData) {
        $allowance->update($updateData);

        $currentAllowanceHistory->update(['started_at' => $newStartAt]);

        [$startDate, $endDate] = $this->calculateDateRange($currentStartAt, $newStartAt);

        $jobs = $this->createLoadUpdateWorkingHistoryJobBatches($startDate, $endDate);

        return Bus::batch($jobs)
            ->then(function () {
                Log::info('Update working history batch successfully');
            })
            ->catch(function (Batch $batch, Throwable $e) {
                Log::error($e->getMessage(), $batch->failedJobIds);
            })->dispatch();
    }
);

预先感谢您的帮助!

php laravel transactions queue jobs
1个回答
0
投票

我认为你可以像这样改变你的代码

try {
        DB::beginTransaction();

        $allowance->update($updateData);
    
        $currentAllowanceHistory->update(['started_at' => $newStartAt]);
    
        [$startDate, $endDate] = $this->calculateDateRange($currentStartAt, $newStartAt);
    
        $jobs = $this->createLoadUpdateWorkingHistoryJobBatches($startDate, $endDate);
    
        Bus::batch($jobs)
        ->then(function () {
            Log::info('Update working history batch successfully');

            DB::commit();
        })
        ->catch(function (Batch $batch, Throwable $e) {
            Log::error($e->getMessage(), $batch->failedJobIds);

            DB::rollback();
        })->dispatch();
    } catch (\Throwable $th) {
        DB::rollback();
    }

而不是

DB::transaction(
function () use ($allowance, $currentAllowanceHistory, $newStartAt, $currentStartAt, $updateData) {
    $allowance->update($updateData);

    $currentAllowanceHistory->update(['started_at' => $newStartAt]);

    [$startDate, $endDate] = $this->calculateDateRange($currentStartAt, $newStartAt);

    $jobs = $this->createLoadUpdateWorkingHistoryJobBatches($startDate, $endDate);

    return Bus::batch($jobs)
        ->then(function () {
            Log::info('Update working history batch successfully');
        })
        ->catch(function (Batch $batch, Throwable $e) {
            Log::error($e->getMessage(), $batch->failedJobIds);
        })->dispatch();
});
© www.soinside.com 2019 - 2024. All rights reserved.