如何在 laravel 中运行多个数据库的迁移?

问题描述 投票:0回答:1

我正在使用laravel-8,我有多个数据库,我在database.php中配置如下

 'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => '',
            'username' => env('DB_USERNAME',''),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => ''
        ],
'databaselist'=>[
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => 'databaselist',
            'username' => env('DB_USERNAME',''),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => ''
        ],

通常,当用户登录时,我的应用程序会正常工作,此时会将数据库名称放入

mysql.database
中,就像我们正在使用的那样。

现在我面临着一个场景,我要开始迁移,我需要在所有数据库中运行迁移,因此我使用 $connection 属性,所以我需要循环它数据库列表连接并将数据库名称传递给

mysql.database
并运行在那个数据库中。任何人都可以帮助我实现这个场景

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTestTable extends Migration
{
    public $connection ='mysql';
    
    public function up()
    {
        Schema::create('test_table', function (Blueprint $table) {
           $table->id();
           $table->string('name');
        });
    }

   
    public function down()
    {
        Schema::dropIfExists('test_table');
    }
}

laravel migration
1个回答
0
投票

您可以使用 Schema::connection() 在不同的数据库上运行迁移,因此通过连接名称进行循环可能会实现此目的。

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTestTable extends Migration
{
    public $connections = ['mysql', 'databaselist'];
    
    public function up()
    {
        foreach($this->connections as $connection) {
            Schema::connection($connection)->create('test_table', function (Blueprint $table) {
                $table->id();
                $table->string('name');
            });

        }
    }

   
    public function down()
    {
        foreach($this->connections as $connection) {
            Schema::connection($connection)->dropIfExists('test_table');
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.