I work on several applications with several databases, where I have a main one DB
, which consists of a table of tenants, and then a new one is created for each tenant created DB
. I write a seed file for this, and I run it 3 times to create 3 Tenants and the next 3 DB
for them.
It works great for the first time. A new tenant is created mainly DB
. A new one DB
is created using a username
new tenant. DB
also migrated
with a command call Artisan
from code. But in the next two cycles, tenants are created mainly DB
, and a new one is also created for them DB
, but the command call Artisan
does not transfer DB
.
public function run()
{
$faker = Faker::create();
$tenants = App\Tenant::all();
$tenants->each(function($tenant){
DB::statement('DROP DATABASE IF EXISTS ' . $tenant->username);
});
DB::table('tenant')->truncate();
for($i = 0; $i < 3; $i++){
$company = $faker->company();
$description = $faker->text();
$logo = $faker->imageUrl(50, 50);
$username = str_random(8);
\Config::set('database.default', 'archive');
echo 'Creating tenant ' . $i . "\r\n";
Tenant::create([
'name' => $company,
'description' => $description,
'logo' => $logo,
'username' => $username,
]);
DB::statement('CREATE DATABASE ' . $username);
\Config::set('database.connections.tenant.database', $username);
\Config::set('database.default', 'tenant');
echo 'Migrating tenant ' . $i . "\r\n";
\Artisan::call('migrate', [
'--path' => 'database/migrations/tenants'
]);
echo "\r\n";
}
}
What am I doing wrong here. It works great for the first time. And then the last two times are created only DB
, but not transferred. Only the first has been successfully transferred from this DB
. And no mistake is thrown from the artisan.
The command line output is as follows:
Creating tenant 0
Migrating tenant 0
Creating tenant 1
Migrating tenant 1
Creating tenant 2
Migrating tenant 2
source
share