【问题标题】:Connect to a lot of databases simultaneously in Laravel 5.2在 Laravel 5.2 中同时连接到很多数据库
【发布时间】:2023-04-02 18:42:02
【问题描述】:

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

我阅读了所有关于 on the fly database connectionmultidatases connections 的信息,但我不知道。

我的逻辑是这样的:

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

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

【问题讨论】:

    标签: php mysql database laravel


    【解决方案1】:

    简介 - 2 个连接

    假设您需要 2 个连接:defaultcustomized,您将像往常一样在 config/database.php 中提供它们的配置,那么您需要:

    >>> 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"
    

    更多连接

    您可以在上面看到需要做什么。在您的情况下,您可以简单地将 whole connection config 用于您需要的每个新连接,它会按预期工作:

    >>> config(['database.connections.on_the_fly' => [
    >>>    'database' => 'provided_on_the_fly',
    >>>    ...
    >>> ]])
    => null
    
    >>> DB::connection('on_the_fly')->getDatabaseName()
    => "provided_on_the_fly"
    

    口才

    如果您想为您的 Eloquent 模型使用自定义连接,您可以使用 SomeModel::on('on_the_fly')->find($id)(获取的模型 instance 将使用该连接进行所有后续操作)

    【讨论】:

    • 谢谢你 Jarek 我很荣幸得到你的回答你在不同的情况下帮助了我很多
    猜你喜欢
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 2018-02-26
    • 2016-09-04
    • 1970-01-01
    • 2018-06-14
    • 2016-07-29
    • 2017-04-11
    相关资源
    最近更新 更多