0

我正在构建一个 Laravel 包。我需要发布我的自定义迁移。一个迁移需要运行另一个迁移,因为它具有外键约束。

在我的服务提供商中,我正在这样做:

public function boot(Filesystem $filesystem)
    {
        $this->loadMigrationsFrom(dirname(__DIR__).'/migrations');
        $this->publishMigrations($filesystem);    
    }


private function publishMigrations(Filesystem $filesystem)
    {
        if (! class_exists('CreateReferencedTable')) {
            $this->publishes([
                __DIR__ . '/../database/migrations/create_referenced_table.php.stub' => $this->getMigrationFileName($filesystem, 'referenced')              
            ], 'migrations');
        }
        if (! class_exists('CreateExampleTable')) {
            $this->publishes([
                __DIR__ . '/../database/migrations/create_example_table.php.stub' => $this->getMigrationFileName($filesystem, 'example')           
            ], 'migrations');
        }
    }

    protected function getMigrationFileName(Filesystem $filesystem, string $table_name): string
    {
        $timestamp = date('Y_m_d_His');
        return Collection::make($this->app->databasePath().DIRECTORY_SEPARATOR.'migrations'.DIRECTORY_SEPARATOR)
            ->flatMap(function ($path, $table_name) use ($filesystem) {
                return $filesystem->glob($path.'*_create_'.$table_name.'_table.php');
            })->push($this->app->databasePath()."/migrations/{$timestamp}_create_{$table_name}_table.php")
            ->first();
    }

然后我跑

php artisan vendor:publish --provider="FedericoArona\MyPackage\Providers\MyServiceProvider" --tag="migrations"

问题是表是使用完全相同的时间戳创建的,因此它们将按名称排序。这意味着“示例”迁移将在“引用”迁移之前创建。

显然,这意味着当我运行迁移时,它们将失败,因为“示例”迁移需要在“引用”之后运行。

我该如何解决?谢谢。

4

1 回答 1

0

我所做的唯一方法是破解:调整时间戳。我将迁移次数放入提供程序的属性中

$this->migrationCount

然后减少时间戳(所以如果滴答计数器在执行过程中增加,它仍然是不同的):

    private function migratePath(string $file): string
    {
        $timeKludge = date('Y_m_d_His', time() - --$this->migrationCount);
        return database_path(
            'migrations/' . $timeKludge . "_$file.php"
        );
    }

它不漂亮,但它有效。

于 2022-01-29T05:18:28.543 回答