在Laravel 5.2中同时连接到许多数据库 [英] Connect to a lot of databases simultaneously in Laravel 5.2

查看:97
本文介绍了在Laravel 5.2中同时连接到许多数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了很多方法可以从整个Internet上的config/database.php文件中更改默认连接,但是我不想使用多租户应用程序,因此我需要同时连接到很多数据库,而我缺乏使代码正常工作的经验.到目前为止,我已经在我的默认数据库中创建了名为DATABASES的模型控制器和表,该数据库一直需要连接,现在我在其中存储了应用程序中的配置选项,现在我需要设置这些连接,但无法完成.

I have found a lot of ways to change the default connection from the config/database.php file from all over the internet, but I don't want a multitenant app I need to connect to a lot of databases simultaneously and I lack the experience to get the code working. I have created so far model controller and table named DATABASES in my default database where I need to be connected all the time, where I store the configuration options from my application now I need to set up these connections and I can't do it.

我在上阅读了所有内容飞行数据库连接多数据连接,但我不知道

我的逻辑是这样:

  1. 在我的(默认)数据库中的表数据库中发送新数据库I的配置数据选项.
  2. 使用复选框启用此数据库.
  3. 显示我的默认数据库和新的ENABLED连接中的用户.
  4. 禁用第二个或第三个连接,但始终可以访问我的默认数据库.

我不需要代码,我不需要指导,希望有人理解我需要做什么!

I don't need code I need guidance, hope someone understand what I need to do!

推荐答案

简介-2个连接

假设您需要2个连接:默认自定义,则可以像往常一样在config/database.php中提供它们的配置,那么您需要:

Intro - 2 connections

Assuming you need 2 connections: default and customized, you'd provide their config in your config/database.php as usually, then you need:

>>> DB::connection()->getDatabaseName()
=> "default"

>>> DB::connection('custom')->getDatabaseName()
=> "customized"

// change the config...
>>> config(['database.connections.custom.database' => 'new_customized_db'])
=> null

// ...but once the connection is already open, config change doesn't affect it...
>>> DB::connection('custom')->getDatabaseName()
=> "customized"

// ...so we need to get rid of existing connection completely (reconnect() won't work)
>>> DB::purge('custom')
=> null

>>> DB::connection('custom')->getDatabaseName()
=> "new_customized_db"


更多连接

上面,您可以看到需要做的事情.对于您的情况,您只需为所需的每个新连接放置整个连接配置,它将按预期工作:


More connections

Above you can see what needs to be done. In your case, you can simply put whole connection config for each new connection you need, and it will work as expected:

>>> config(['database.connections.on_the_fly' => [
>>>    'database' => 'provided_on_the_fly',
>>>    ...
>>> ]])
=> null

>>> DB::connection('on_the_fly')->getDatabaseName()
=> "provided_on_the_fly"


口才

如果您要对口才模型使用自定义连接,则可以使用SomeModel::on('on_the_fly')->find($id)(获取的模型实例将使用该连接进行所有后续操作)


Eloquent

If you want to use custom connection for your Eloquent models you can use SomeModel::on('on_the_fly')->find($id) (fetched model instance will use the connection for all subsequent operations)

这篇关于在Laravel 5.2中同时连接到许多数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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