【问题标题】:Laravel 8 - Disable migrations for specific packageLaravel 8 - 禁用特定包的迁移
【发布时间】:2021-08-10 10:06:14
【问题描述】:

场景如下:
我正在构建一个软件,其中前端和执行工作的程序相互分离。为了让前端能够使用工作程序的模型,我构建了一个包含它们的包。该软件包的提供程序具有以下代码:

public function boot()
    {
        if($this->app->runningInConsole()){
            $this->loadMigrationsFrom(__DIR__ . '/MyPackageMigrations');
        }
    }

现在我的问题是,我希望在工作程序中运行artisan migrate 命令时运行这些迁移,而不是在 UI 程序中运行,因为这两个数据库也是相互分离的。有没有办法在 UI 程序中抑制这些迁移?

问候

【问题讨论】:

    标签: laravel laravel-migrations


    【解决方案1】:

    您可以使用$this->puiblishes(),而不是在ServiceProviderboot() 方法中使用loadMigrationsFrom(),它可以让您控制发布迁移,而不是让它们自动加载。

    public function boot()
    {
        if ($this->app->runningInConsole()) {
            $this->publishes([
                __DIR__ . '/../database/migrations/create_models_table.php.stub' 
                    => database_path('migrations/' . date('Y_m_d_His', time()) . 'create_models_table.php'),
                // you can add any number of migrations here
            ], 'migrations');
        }
    }
    

    那么你需要做的就是在你想要使用迁移的项目中发布迁移:

    php artisan vendor:publish --provider="Husky110\Husky110Package\Husky110PackageServiceProvider" --tag="migrations"
    

    更新

    您可以通过执行以下操作来检查是否存在迁移:

    if (!class_exists('CreateModelsTable')) {
        // perform migration
    }
    

    如果您的迁移会改变表的结构,您可能会这样做:

    if (!class_exists('AlterModelsTableAddField')) {
        // perform migration
    }
    

    【讨论】:

    • 好主意,但我想知道当我添加新迁移时会发生什么,因为该包目前处于某种变化状态(也称为开发)...将时间戳设置为一个静态值,所以迁移不会被发布两次?我正在考虑将 pubish- 和 migrate-commands 添加到 worker 的 composer.json ...
    • @Husky110 我已经更新了我的答案给你一个可能的解决方案。
    猜你喜欢
    • 2021-02-28
    • 2018-01-10
    • 2021-11-07
    • 2014-11-22
    • 2021-07-19
    • 2018-04-20
    • 2017-11-17
    • 2019-04-09
    • 2016-09-11
    相关资源
    最近更新 更多