在Laravel中动态更改数据库连接 [英] Change the Database Connection Dynamically in Laravel
问题描述
我有一个具有登录表和每个用户相应数据库设置的主数据库.登录时,我应该动态更改从表中获取的数据库设置. 我可以更改数据库连接,但是这种连接不会持久.
I have the master database with login table and corresponding database settings for each user. On login I should dynamically change the db settings fetching from the table. I can change the db connection but this is not persisting.
Config::set("database.connections.mysql", [
'driver' => 'mysql',
"host" => $usr_host,
"database" => $usr_database,
"username" => $usr_username,
"password" => $usr_password,
...
]);
当他/她在应用程序中注册时,会为每个用户创建一个新数据库,因此我没有在config/database.php
edit: New database is created for each user when he/she registers with the app and thus i dont have the database connection for each user defined in the config/database.php
推荐答案
您可以使用默认数据库进行用户登录,并为数据库名称添加一个新字段.然后,每当需要查询其他数据库时,只需更改数据库连接即可.
Well you can use the default database for user login and have a new field for the database name. Then whenever you need to query a different database, you can just change your db connection.
类似这样的东西
$someModel = new SomeModel;
$databaseName = "mysql2"; // Dynamically get this value from db
$someModel->setConnection($databaseName);
$something = $someModel->find(1);
您可以在此处了解更多信息. http://fideloper.com/laravel-multiple-database-connections
You can read more about it here. http://fideloper.com/laravel-multiple-database-connections
这篇关于在Laravel中动态更改数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!