我需要在运行时更改laravel 5数据库连接。
你知道吗?
请与我分享。
谢谢。
您可以在运行时使用更改连接详细信息
Config::set('database.connections.mysql.database', 'other_database');
但不要忘记之前运行purge
以删除缓存
DB::purge('mysql');
更新:这个答案来自2015年!我已经好几年没有使用Laravel了,我也不了解最新的最佳实践。这个答案一直被投票支持,所以我认为它有效,但请谨慎行事。
好吧,我的直接答案是:不要您有可能通过更改数据模型和使用一些更高级的关系来完成任务。在不知道自己想做什么的情况下很难判断,但在我看来,总的来说,这是一个坏主意,特别是如果你计划使用雄辩的模型等
也就是说,在某些情况下,如果您确实需要更改另一个数据库中的数据或执行一些原始查询,则可以使用DB::connection()
方法。类似于:
$data = DB::connection('another_connection')->select(...);
您可以在database.php
文件中指定another_connection
变量。像这样:
<?php
return array(
'default' => 'mysql',
'connections' => array(
# Your regular connection
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database',
'username' => 'user',
'password' => 'password'
'charset' => 'utf8',
),
# Your new connection
'another_connection' => array(
'driver' => 'mysql',
'host' => 'another_host',
'database' => 'another_db',
'username' => 'user1',
'password' => 'password1'
'charset' => 'utf8',
),
),
);
您甚至可以使用protected $connection = 'another_connection';
为每个有说服力的模型指定一个连接,也可以为运行时创建/查询的每个模型实例指定连接
$user = new User;
$user->setConnection('another_connection');
$user1 = $user->find(1);
但话说回来,我个人认为这不是一个好主意,而且在我看来,随着应用程序的复杂性增加,一切都可能变得一团糟,很快就会分崩离析。
自Laravel 5.x或6.x 以来,您可以这样更改它
config(['database.default' => 'databasename']);
其中,必须在connections
数组中的config/database
中指定databasename
。
我们有一个类似的场景,在那里查找历史数据,我们更改数据库。我们在模型中使用以下内容:
public function inventory($db, $id) {
return DB::table($db . '.inventory')->where('inventoryid', $id)->get();
}
然后,在代码上,我们发送$db作为参数:
$inventory = Inventory::inventory('data_2016', 2);
这样,就不需要为每个不同的数据库定义连接,也不需要修改数据库配置文件。
唯一的缺点是不能直接使用模型,而是必须使用DB助手。