Use one Laravel migrations table per database

前端 未结 1 1504
盖世英雄少女心
盖世英雄少女心 2020-11-30 01:36

I work in a project that uses multiple databases. It seems like Laravel only uses the migrations-table in the database that is set as default. I would like one migrations ta

相关标签:
1条回答
  • 2020-11-30 01:53

    Use the --database parameter with the migrate command and store the migrations for each database in separate directories.

    You could have separate directories in app/database/migrations for each of your database (in your case db1 and db2) and store the appropriate migrations in each directory. Then you could run the migrations like this:

    artisan migrate --database="db1" --path="app/database/migrations/db1"
    artisan migrate --database="db2" --path="app/database/migrations/db2"
    

    This way your migrations table will be independent for each database.

    If you want to go the extra mile and automate the process you could create your custom command that will run all the migrations at once. You can create the command like this (use make:console for Laravel 5.0 up to 5.2 or make:command for Laravel 5.2+):

    artisan command:make MigrateAllCommand --command=migrate:all
    

    This will create a new file app/commands/MigrateAllCommand.php. Your command's fire method would look something like this:

    public function fire()
    {
        foreach (Config::get('database.connections') as $name => $details)
        {
            $this->info('Running migration for "' . $name . '"');
            $this->call('migrate', array('--database' => $name, '--path' => 'app/database/migrations/' . $name));
        }
    }
    

    This will work provided the name of the database configuration key is the same as the migration directory name. You can then just call it like this:

    artisan migrate:all
    

    You can check the Laravel Command Docs for more info.

    0 讨论(0)
提交回复
热议问题