Laravel: Run migrations on another database

前端 未结 8 2062
有刺的猬
有刺的猬 2020-12-29 23:15

In my app every user has its own database that created when user registered. Connection and database data (database name, username, password) are saved in a table in default

8条回答
  •  自闭症患者
    2020-12-29 23:46

    I think I finally figured out this mess... This solution doesn't need a configuration for each tenant's database and has to be run only once.

    class MigrationBlah extends Migration {
      public function up() {
        $dbs = DB::connection('tenants')->table('tenants')->get();
        foreach ($dbs as $db) {
          Schema::table($db->database . '.bodegausuarios', function($table){
            $table->foreign('usuario')->references('usuarioid')->on('authusuarios');
          });
        }
      }
    }
    

    Where I have a connection named "tenants" on my database.php, which contains the database name of all of my tenants. I have the default connection set to my tenants database as well. That database is the one responsible for taking care of the migrations table.

    With the foreach statement, it goes through the tenant databases and runs the migration on each one.

    On your default connection, you should configure a user that has access to all tenant's databases for it to work.

提交回复
热议问题