laravel 5在运行时更改数据库名称 [英] laravel 5 Changing database name in runtime

查看:179
本文介绍了laravel 5在运行时更改数据库名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以更改连接的数据库名称而不是添加另一个?
如果在Config.database.connections中添加3个或5个数据库是可以的,但是如果我有100个或更多的数据库,该怎么办?
由于所有人都使用相同的HOST,USERNAME和PASSWORD,因此是否可以动态地更改数据库名称并在整个会话期间使用它?
我尝试过

is there a way to change the database name of a connection instead of adding another? It's okay if I add 3 or 5 databases in Config.database.connections, but what If I have 100 or more databases I am working with? Since all use the same HOST, USERNAME and PASSWORD, is there anyway to just change the database name dynamically and work with that during the whole session? I tried

Config::set('database.connections.mysql.database', 'database1');

但是当我尝试使用查询时,它仍然使用默认查询。

but when I try using queries , it still uses the default one.

推荐答案

如果仍然有人在寻找这个问题的答案,答案在这里:

If anyone still is searching for the answer for this question, answer is here:

您可以在运行时更改数据库名称(非连接),如下所示:

You can change database name(not connection) at run time as follows:

在控制器或中间件顶部导入以下类:

Import following classes on top of your controller or middleware:

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;

然后在内部函数中,如下更改数据库名称:

Then inside function, change database name as follows:

DB::disconnect('mysql');//here connection name, I used mysql for example
Config::set('database.connections.mysql.database', $dbName);//new database name, you want to connect to.

此后,每当您进行查询以从任何表中提取任何数据时,它将搜索到新数据库中

After this whenever you will make query to extract any data from any table, it will search into new database provided.

请注意,这是为了在运行时更改 SAME 连接中的数据库名称。

Please note, this is for changing database name in SAME connection while runtime.

我希望对您有帮助

这篇关于laravel 5在运行时更改数据库名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆