【问题标题】:How can I call Artisan::call(...) more than once? (Migrate and then Seed)如何多次调用 Artisan::call(...) ? (迁移然后播种)
【发布时间】:2018-12-06 23:56:49
【问题描述】:

我发现使用Artisan::call() 命令进行迁移,然后再次设置种子会导致正确的迁移,但数据库从未设置种子。这可能是一个错误,或者有办法刷新上一个命令。

例如:

Artisan::call('migrate', [
    '--database'  => 'tenant',
    '--path'      => 'database/tenantMigrations',
    '--force'     => true,
]);

然后:

Artisan::call('db:seed', [
    '--database'  => 'tenant',
    '--class' => 'TenantSeeder',
]);

如您所见,我在新创建的租户数据库上运行这些命令来“配置”它。这些命令中的每一个都单独工作,但不能一起工作。

我已尝试查找有关加入这两个命令的更多文档,同时能够指定播种机的类。这可能看起来像:

Artisan::call('migrate', [
    '--database'  => 'tenant',
    '--path'      => 'database/tenantMigrations',
    '--force'     => true,
    '--seed'      => true,
    '--class'     => 'TenantSeeder', // this is the only one I can't do, which is critical
]);

我也尝试过像这样运行播种机:

(new \TenantSeeder)->run();

我收到错误:Call to a member function line() on null

值得注意的是,所有这些都在我本地的 Homestead 环境中正常工作,但在 Forge 管理的 Digital Ocean 服务器上却无法正常工作。

编辑

我当前的解决方案是将我的播种器逻辑放在常规类(不扩展基本播种器类)中,并如上所示调用它们。

【问题讨论】:

    标签: laravel laravel-artisan laravel-seeding


    【解决方案1】:

    您可以创建一个包含所有所需选项的包装器命令,然后分别调用migrateseed 等命令:

    php artisan make:command MigrateAndSeedCommand
    

    该类可能类似于:

    class MigrateAndSeedCommand extends Command
    {
        protected $signature = 'migrateandseed {--database=} {--path=} {--force} {--seed} {--class=}';
    
        public function handle()
        {
            Artisan::call('migrate', [
                '--database'  => $this->option('database'),
                '--path'      => $this->option('path'),
                '--force'     => $this->option('force'),
            ]);
            Artisan::call('db:seed', [
                '--database'  => $this->option('database'),
                '--class'     => $this->option('class'),
            ]);
        }
    }
    

    可通过以下方式使用:

    php artisan migrateandseed --database=tenants --path=database/tenantMigrations --force --seed --class=TenantSeeder
    
    // or 
    
    Artisan::call('migrateandseed', [
        '--database'  => 'tenant',
        '--path'      => 'database/tenantMigrations',
        '--force'     => true,
        '--seed'      => true,
        '--class'     => 'TenantSeeder',
    ]);
    

    编辑

    使用$this 代替Artisan,以及可选地对命令进行排队:

    // or  $this->queue
    $this->call('db:seed', [
        '--database'  => $this->option('database'),
        '--class'     => $this->option('class'),
    ]);
    

    Calling Commands From Other Commands

    【讨论】:

    • 问题是,两条 Artisan 命令无法运行。第二个被跳过。 (见原帖)
    • 查看我的更新,不要使用Artsian门面,而是使用$this
    猜你喜欢
    • 2014-12-17
    • 2019-06-30
    • 2016-03-30
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 2017-01-06
    • 2013-09-16
    • 2023-03-12
    相关资源
    最近更新 更多