php Laravel迁移的任何失败的回滚事务

23c0lvtd  于 11个月前  发布在  PHP
关注(0)|答案(1)|浏览(71)

所以,我们的想法是,如果迁移失败,回滚任何更改,即使我们有30个迁移,但一个迁移失败,它应该什么也不迁移。
我正在努力:

\DB::connection($this->getConnectionName($databaseName))->beginTransaction();
    $migrator = app(Migrator::class);
    $migrator->setConnection($this->getConnectionName($databaseName));

    try {
        $migrator->run('database/workspace/migrations', [
            '--force' => env('APP_ENV') === 'production',
        ]);

        \DB::connection($this->getConnectionName($databaseName))->commit();
    } catch (\Exception $exception) {
        \DB::connection($this->getConnectionName($databaseName))->rollBack();
        throw $exception;
    }

字符串
但在这种情况下,in表示没有任何活动的事务。
如何将迁移命令作为事务处理?
我也试过

$migrator = app(Migrator::class);
        $migrator->setConnection($this->getConnectionName($databaseName));

        try {
            $migrationsPath = 'database/workspace/migrations';
            $files = $migrator->getMigrationFiles($migrationsPath);

            $migrations = $migrator->pendingMigrations($files, $migrator->getRepository()->getRan());

            $batch = $migrator->getRepository()->getNextBatchNumber();

            foreach ($migrations as $migration) {
                $migrator->runUp($migration, $batch, 0);
            }

            \DB::connection($this->getConnectionName($databaseName))->commit();
        } catch (\Exception $exception) {
            \DB::connection($this->getConnectionName($databaseName))->rollBack();
            throw $exception;
        }


迁移仍然没有提交和回滚。

bfhwhh0e

bfhwhh0e1#

你可以试试这个:

\DB::connection($this->getConnectionName($databaseName))->beginTransaction();
$migrator = app(Migrator::class);
$migrator->setConnection($this->getConnectionName($databaseName));

try {
    $migrationsPath = 'database/workspace/migrations';
    $migrations = $migrator->getMigrationFiles($migrationsPath);

    foreach ($migrations as $file) {
        $migration = $migrator->resolve($migrator->getMigrationName($file));
        if ($migrator->isRun($file)) {
            continue;
        }

        $migrator->runUp($migration, $file, 0);
    }

    \DB::connection($this->getConnectionName($databaseName))->commit();
} catch (\Exception $exception) {
    \DB::connection($this->getConnectionName($databaseName))->rollBack();
    throw $exception;
}

字符串

相关问题