问题
I am working on laravel 4 app, In that i wan to allow the user to register for the app and when they register the app should allow a new empty database to the registered user,I am using mysql for backend I know the following code to set the database connection
Config::set('database.connections', ConnectionArray);
And to set it as default
Config::set('database.default', ConnectionKey);
To connect another database manually i can use this way
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database',
'username' => 'root',
'password' => '123456',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
'mysql_tenant1' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'tenant1',
'username' => 'root',
'password' => '123456',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
But i want the app should create database dynamically...
回答1:
Creating the Database itself will be relatively simple. The complexity comes in associating those databases to users somehow, and then pulling those database names and using them in connections. This should help:
In terms of overall strategy, consider creating a new repository with a few functions:
RegisterUser()
- This registers the user with username/password.CreateDatabase($name , $user_id)
- This should create your database and store it's name in a table, and then assign it to the User ID you created in Register User.
You can run raw SQL queries in Laravel with DB::statement()
(i.e - ``DB::statement('create database' . $name);`, so stick that in your CreateDatabase function. I tested this locally and it works just fine.
NOTE: You'll want to do some validation to make sure the database doesn't already exist, or your user is going to (obviously) get an error.
Then, you can pull the Database name from the table by User ID and create connections with it as described in the below SO!
Laravel 4: Multiple Tenant Application, each tenant it's own database and one global database
One thing - when you make a change to your database structure, you're going to have to update each database individually. Note that Artisan allows for this with the --database="database_name"
option.
回答2:
Just have a user_id field in whatever table(DB from what I think you're describing) you want, and use relationships to make it work, a whole bunch of fields in one table(or more than one table) may be FAR more efficient than what you think.
来源:https://stackoverflow.com/questions/20392180/creating-the-database-on-fly