laravel中动态连接多个数据库
我正在构建一个需要连接 2 个数据库的应用程序.第一个是静态的,另一个是动态的.config/database.php 就像
I'm building an application which requires connecting 2 database. first one is static and another one is dynamic. config/database.php is like
'mysql' =>
array (
'driver' => 'mysql',
'host' => '127.0.0.1',
'port' => '3306',
'database' => 'blog',
'username' => 'root',
'password' => '',
'unix_socket' => '',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => NULL,
),
'business2' =>
array (
'driver' => 'mysql',
'host' => '127.0.0.1',
'port' => '3306',
'database' => 'blog2',
'username' => 'root',
'password' => '',
'unix_socket' => '',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => NULL,
),
和型号代码是一样的
Class TableNewData extends Model
{
protected $connection = 'business3';
protected $table = 'table2_data';
public function getData()
{
return $this->get()->toArray();
}
}
如果我提供静态连接详细信息,我可以连接多个数据库,但如果我提供动态连接详细信息,我将无法连接数据库
I am able to connect multiple databases if I give static connection details but I am unable to connect database if I give dynamic connection details like
$connection = Session::get()->connection;
或
$connection=$_SESSION('connection');
在不影响应用程序性能的情况下动态连接多个数据库的最佳方法是什么?
What is the best way to connect multiple databases dynamically without effecting performance of application?
推荐答案
在运行时更改连接的一种方法是通过配置设置值:
One way of changing the connection at runtime is to set the values via the config:
config(['database.connections.mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'my_database'),
'username' => env('DB_USERNAME', 'my_user'),
'password' => env('DB_PASSWORD', 'my_password'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
]]);
这可以应用在中间件中,例如在租户数据库之间动态切换.
This can be applied in a middleware to dynamically switch between tenant databases, for example.
您还可以通过 DB 外观指定连接:
You can also specify a connection via the DB facade:
DB::connection('mysql_2')->select(...);
相关文章