我正在尝试为不同的用户动态创建数据库。(每个用户都有自己的数据库服务器,所以不要问为什么我没有为所有用户使用一个数据库)为了做到这一点,我有一个默认的数据库来存储所有的连接信息。我需要:
- 创建一个新数据库,并在新用户注册时运行所有迁移文件。
- 当模式更新时,在这个默认数据库中记录的所有数据库上运行新的迁移文件。
是否有一种方法可以根据我在默认数据库上的信息动态设置迁移文件的数据库连接?
注:对于"动态设置数据库连接",我不是指你在控制器或类中所做的正常设置。我希望至少能够在目标数据库中创建迁移表,并能够自我检测要运行的迁移文件。
有。首先,需要将连接细节添加到配置中。一旦配置了命名连接,只需在Artisan facade上调用migrate
命令,选择连接的名称(在本例中为"new")作为选项:
use Illuminate'Support'Facades'Artisan;
//...
$new_connection = 'new';
config(["database.connections.$new_connection" => [
// fill with dynamic data:
"driver" => "mysql",
"host" => "",
"port" => "",
"database" => "",
"username" => "",
"password" => "",
"charset" => "utf8",
"collation" => "utf8_unicode_ci",
"prefix" => "",
"strict" => true,
"engine" => null
]]);
Artisan::call('migrate', ['--database' => $new_connection]);
首先需要创建数据库
DB::getConnection()->statement('CREATE DATABASE :schema', array('schema' => $schemaName));
然后更改数据库的名称,如下所示
$config = app('Illuminate'Config'Repository::class);
$config->set('database.connections.mysql.database', UserRepotory::getCurrentDatabase());
您可以像这样或通过laravel的服务容器包含Config
。
最后调用Artisan::call('migrate')
你好,帮你个小忙,
首先在database.php文件中添加'%new_connection%'来处理新连接,以备将来使用。
要动态创建连接,假设你有一个路由,变量$name为数据库名。
步骤1:在路线。并在routes.php
中调用所需的路由url。function appendNewConnection($name){
$path = base_path('config' . DIRECTORY_SEPARATOR . 'database.php');
$contents = file_get_contents($path);
$updatedContents = str_replace('%new_connection%', $name . ''' => [
''driver'' => ''mysql'',
''host'' => ''127.0.0.1'',
''database'' => ''' . $name . ''',
''username'' => ''root'',
''password'' => '''',
''charset'' => ''utf8'',
''collation'' => ''utf8_unicode_ci'',
''prefix'' => '''',
''strict'' => false,
],
''%new_connection%', $contents);
file_put_contents($path, $updatedContents);
}
步骤2:
//to generate migration add below line in top of routes.php
use Illuminate'Support'Facades'Artisan;
add this line in function created above
Artisan::call('migrate', ['--database' => $name]);
关于如何做到这一点,我有一些提示:
1。将有一个全局数据库,您将在其中维护所有用户登录信息,对吧?
2。为数据库名称添加一个额外的字段。
3 。当用户成功登录时,将其数据库详细信息存储在会话中变量。
,
4。动态创建一个数据库文件,并从该会话变量中给出数据库名称:
config(["database.connections.$new_connection" => [
// fill with dynamic data:
"driver" => "mysql",
"host" => "",
"port" => "",
"database" => "",//Here you need to set value of session variable
"username" => "",// credential will be the same for all
"password" => "",// credential will be the same for all
"charset" => "utf8",
"collation" => "utf8_unicode_ci",
"prefix" => "",
"strict" => true,
"engine" => null
]]);
D