Laravel:动态连接数据库 [英] Laravel: connect to databases dynamically
问题描述
我正在Laravel 5(.1)中创建一个应用程序,在该应用程序中需要连接到不同的数据库.唯一的问题是,它不知道必须连接到哪个数据库,因此无法在config中使用database.php.控制器负责使用动态给定的连接详细信息进行连接.
I'm creating an application in Laravel 5(.1) where it is needed to connect to different databases. The only problem is that it's not known which databases it has to connect to, so making use of the database.php in config is not possible. A controller is in charge of making a connection with dynamically given connection details.
如何建立与数据库的新连接,包括使用DB类? (或者这可能)
How can I make a new connection to a database, including making use of the DB class? (Or is this possible)
提前谢谢!
推荐答案
最简单的解决方案是在运行时设置数据库配置. Laravel可能希望从config/database.php
文件中加载这些设置,但这并不意味着您以后无法设置或更改它们.
The simplest solution is to set your database config at runtime. Laravel might expect these settings to be loaded from the config/database.php
file, but that doesn't mean you can't set or change them later on.
从config/database.php
加载的配置存储为database
在Laravel配置中.这意味着config/database.php
中的connections
数组存储在database.connections
中.
The config loaded from config/database.php
is stored as database
in Laravel config. Meaning, the connections
array inside config/database.php
is stored at database.connections
.
因此,您可以像这样轻松地覆盖/更改这些连接:
So you can easily override/change these connections like this:
Config::set("database.connections.mysql", [
"host" => "...",
"database" => "...",
"username" => "...",
"password" => "..."
]);
从此以后,使用此mysql
连接的所有Eloquent模型都将使用此新的数据库连接配置.
From there on out, any Eloquent models that use this mysql
connection will be using this new database connection config.
如果可能,我建议在服务提供商中进行此操作.
I'd recommend doing this in a Service Provider if possible.
这篇关于Laravel:动态连接数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!