除了一个之外,如何运行laravel migration和DB seeder

Nik*_*aut 11 php laravel laravel-seeding laravel-migrations

我要运行许多迁移和播种器文件,虽然我需要运行所有文件,但目前我需要跳过一个迁移和播种器.

我如何从laravel migration和db seeder命令中跳过一个文件.

我不想从迁移或种子文件夹中删除文件以跳过该文件.

Lom*_*baX 8

Laravel没有为您提供默认方法.但是,您可以创建自己的控制台命令和播种器来实现它.
假设你有这个默认DatabaseSeeder类:

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        $this->call(ExampleTableSeeder::class);
        $this->call(UserSamplesTableSeeder::class);
    }
}
Run Code Online (Sandbox Code Playgroud)

目标是创建一个覆盖"db:seed"的新命令,并将一个新参数"except"参数传递给DatabaseSeeder该类.

这是我在Laravel 5.2实例上创建的最终代码,并尝试:

命令,放入app/Console/Commands,不要忘记更新你的Kernel.php:

namespace App\Console\Commands;
use Illuminate\Console\Command;
class SeedExcept extends Command
{
    protected $signature = 'db:seed-except {--except=class name to jump}';
    protected $description = 'Seed all except one';
    public function handle()
    {
        $except = $this->option('except');
        $seeder = new \DatabaseSeeder($except);
        $seeder->run();
    }
}
Run Code Online (Sandbox Code Playgroud)

DatabaseSeeder

use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
    protected $except;

    public function __construct($except = null) {
        $this->except = $except;
    }

    public function call($class)
    {
        if ($class != $this->except)
        {
            echo "calling $class \n";
            //parent::call($class);  // uncomment this to execute after tests
        }
    }

    public function run()
    {
        $this->call(ExampleTableSeeder::class);
        $this->call(UserSamplesTableSeeder::class);
    }
}
Run Code Online (Sandbox Code Playgroud)

代码,你会发现我评论了调用种子的行,并为测试目的添加了一个echo.

执行此命令:

php artisan db:seed-except

会给你:

调用ExampleTableSeeder
调用UserSamplesTableSeeder

但是,添加"除":

php artisan db:seed-except --except = ExampleTableSeeder

会给你

调用UserSamplesTableSeeder

这可以覆盖类的默认call方法,DatabaseSeeder并且仅当类的名称不在$ except变量中时才调用父类.变量由SeedExceptcustom命令填充.

关于迁移,事情是相似的,但有点困难.

我现在不能给你测试代码,但事情是:

  • 您创建一个migrate-except覆盖MigrateCommand该类的命令(命名空间Illuminate\Database\Console\Migrations,位于vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/MigrateCommand.php).
  • MigrateCommand需要一个Migrator对象(命名空间照亮\数据库\迁移,路径供应商/ laravel /框架/ SRC /照亮/数据库/迁移/ Migrator.php)在构造(通过IoC的注入).本Migrator类拥有读取该文件夹内的所有迁移和执行它的逻辑.这个逻辑在run()方法内部
  • Migrator例如MyMigrator,创建一个子类,并覆盖该run()方法以跳过使用特殊选项传递的文件
  • 覆盖__construct()你的方法MigrateExceptCommand并传递你的MyMigrator:public function __construct(MyMigrator $migrator)

如果我有时间,我会在赏金结束之前添加一个例子的代码

正如所承诺的那样编辑,这是迁移的一个例子:

MyMigrator类,扩展Migrator并包含跳过文件的逻辑:

namespace App\Helpers;
use Illuminate\Database\Migrations\Migrator;
class MyMigrator extends Migrator
{
    public $except = null;

    // run() method copied from it's superclass adding the skip logic
    public function run($path, array $options = [])
    {
        $this->notes = [];

        $files = $this->getMigrationFiles($path);

        // skip logic
        // remove file from array
        if (isset($this->except))
        {
            $index = array_search($this->except,$files);
            if($index !== FALSE){
                unset($files[$index]);
            }
        }
        var_dump($files); // debug

        $ran = $this->repository->getRan();
        $migrations = array_diff($files, $ran);
        $this->requireFiles($path, $migrations);

        //$this->runMigrationList($migrations, $options);  // commented for debugging purposes
    }
}
Run Code Online (Sandbox Code Playgroud)

MigrateExcept自定义命令

namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Database\Console\Migrations\MigrateCommand;
use App\Helpers\MyMigrator;
use Illuminate\Database\Migrations\Migrator;
use Symfony\Component\Console\Input\InputOption;

class MigrateExcept extends MigrateCommand
{
    protected $name = 'migrate-except'; 

    public function __construct(MyMigrator $migrator)
    {   
        parent::__construct($migrator);
    }

    public function fire()
    {
        // set the "except" param, containing the name of the file to skip, on our custom migrator
        $this->migrator->except = $this->option('except');
        parent::fire();
    }

    // add the 'except' option to the command
    protected function getOptions()
    {
        return [
            ['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to use.'],

            ['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production.'],

            ['path', null, InputOption::VALUE_OPTIONAL, 'The path of migrations files to be executed.'],

            ['pretend', null, InputOption::VALUE_NONE, 'Dump the SQL queries that would be run.'],

            ['seed', null, InputOption::VALUE_NONE, 'Indicates if the seed task should be re-run.'],

            ['step', null, InputOption::VALUE_NONE, 'Force the migrations to be run so they can be rolled back individually.'],

            ['except', null, InputOption::VALUE_OPTIONAL, 'Files to jump'],
        ];
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,您需要将此添加到服务提供者以允许Laravel IoC解析依赖关系

namespace App\Providers;
use App\Helpers\MyMigrator;
use App\Console\Commands\MigrateExcept;


class CustomServiceProvider extends ServiceProvider
{
    public function boot()
    {
        parent::boot($events);

        $this->app->bind('Illuminate\Database\Migrations\MigrationRepositoryInterface', 'migration.repository');
        $this->app->bind('Illuminate\Database\ConnectionResolverInterface', 'Illuminate\Database\DatabaseManager');

        $this->app->singleton('MyMigrator', function ($app) {
            $repository = $app['migration.repository'];
            return new MyMigrator($repository, $app['db'], $app['files']);
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

不要忘记Commands\MigrateExcept::class在Kernel.php中添加

现在,如果你执行

php artisan migrate-except

你有:

array(70) {
  [0] =>
  string(43) "2014_04_24_110151_create_oauth_scopes_table"
  [1] =>
  string(43) "2014_04_24_110304_create_oauth_grants_table"
  [2] =>
  string(49) "2014_04_24_110403_create_oauth_grant_scopes_table"
  ...
Run Code Online (Sandbox Code Playgroud)

但添加了除了参数:

php artisan migrate-except --except = 2014_04_24_110151_create_oauth_scopes_table

array(69) {
  [1] =>
  string(43) "2014_04_24_110304_create_oauth_grants_table"
  [2] =>
  string(49) "2014_04_24_110403_create_oauth_grant_scopes_table"
Run Code Online (Sandbox Code Playgroud)

所以,回顾一下:

  • 我们创建一个自定义migrate-except命令,MigrateExcept类,扩展MigrateCommand
  • 我们创建一个自定义迁移器类MyMigrator,扩展标准的行为Migrator
  • 当MigrateExcept是fi​​re()时,传递文件名以跳到我们的MyMigrator
  • MyMigrator覆盖run()方法Migrator并跳过传递的迁移
  • 更多:因为我们需要向Laravel IoC指示新创建的类,所以它可以正确地注入它们,我们创建一个服务提供者

代码经过测试,因此它应该在Laravel 5.2上正常工作(希望剪切和粘贴正常工作:-) ...如果有任何疑问发表评论