我正在尝试为不同的用户动态创建数据库。 (每个用户都有自己的数据库服务器,所以不要问为什么我没有为所有用户使用单个数据库)为此,我有一个存储所有连接信息的默认数据库。我需要:
有没有办法可以根据默认数据库中的信息动态设置迁移文件的数据库连接?
P.S。对于"动态设置数据库连接",我不像在控制器或类中那样表示正常设置。我希望能够至少在目标数据库中创建迁移表并能够自我检测要运行的迁移文件。
答案 0 :(得分:6)
是的。首先,您需要将连接详细信息添加到配置中。配置完命名连接后,只需在Artisan外观上调用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]);
答案 1 :(得分:1)
首先,您需要创建数据库
DB::getConnection()->statement('CREATE DATABASE :schema', array('schema' => $schemaName));
然后像这样
动态更改数据库的名称$config = app(\Illuminate\Config\Repository::class);
$config->set('database.connections.mysql.database', UserRepotory::getCurrentDatabase());
您可以像这样包含Config
或通过laravel的服务容器。
最后你打电话给Artisan::call('migrate')
答案 2 :(得分:1)
对你很有帮助,
首先在database.php文件中添加'%new_connection%'以处理新连接以供将来使用。
要动态创建连接,假设您有一个带有变量$ name的路由,用于数据库名称。
第1步: 在routes.file中我创建并在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]);
答案 3 :(得分:0)
我在这里有一些关于你如何做到这一点的线索:
<强> 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
]]);
Bingo你现在准备好了:D
答案 4 :(得分:-2)
在app / config / database.php中定义连接
<?php
return array(
'default' => 'mysql',
'connections' => array(
# Our primary database connection
'mysql' => array(
..........
),
# Our secondary database connection
'mysql2' => array(
.......
),
),
);?>
迁移中
Schema::connection('mysql2')->create('some_table', function($table)
{
$table->increments('id'):
});