我正在构建一个 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"
问题是表是使用完全相同的时间戳创建的,因此它们将按名称排序。这意味着“示例”迁移将在“引用”迁移之前创建。
显然,这意味着当我运行迁移时,它们将失败,因为“示例”迁移需要在“引用”之后运行。
我该如何解决?谢谢。