问题
I want dynamically create new database, database user and password with privileges, create some tables in new database on the fly in Laravel 4 for every new user. This is for a multi tenant website.
Whats the best solution?
thanks.
回答1:
This is not your first database connection it's easy, but you'll have to execute raw statements because database creation is no available as connection methods:
DB::statement(DB::raw('CREATE DATABASE <name>'));
To do that you can use a secondary connection:
<?php
return array(
'default' => 'mysql',
'connections' => array(
'mysql' => array(
'driver' => 'mysql',
'host' => 'host1',
'database' => 'database1',
'username' => 'user1',
'password' => 'pass1'
),
'store' => array(
'driver' => 'mysql',
'host' => 'host2',
'database' => 'database2',
'username' => 'user2',
'password' => 'pass2'
),
),
);
Then you can, during application bootstrap, change the database of the secondary connection:
DB::connection('store')->setDatabaseName($store);
or
Config::set('database.connections.store', $store);
And use the secondary connection in your queries:
$user = User::on('store')->find(1);
or
DB::connection('store')->select(...);
来源:https://stackoverflow.com/questions/25821291/create-new-database-on-the-fly-in-laravel-4