Laravel中的动态数据库连接 [英] Dynamic database connection in Laravel

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

问题描述

我知道在Laravel中,您可以通过在config/database.php文件中指定它们,然后使用DB::connection('my_conn_name')来使用多个数据库连接,但是仍然可以使用在config/database.php文件中未指定的连接吗?

I know that in Laravel you can use multiple database connections by specifying them in the config/database.php file, then using DB::connection('my_conn_name'), but is there anyway to use a connection that is not specified in the config/database.php file?

我正在编写一个归档应用程序,因此用户可以指定他们要用于该进程的连接(主机,用户和密码),并且希望可以从show databases返回所提供的结果连接.

I am writing an archiving application, so the user can specify what connection they would like to use for the process (host, user and password), and I am hoping that I can return the results from show databases for the supplied connection.

推荐答案

用户指定了db参数后,您可以将其存储在会话中以填充config/database.php处的自定义连接:

After the user has specified the db parameters you could store it in a session to populate a custom connection at config/database.php:

'connections' => [

    'mysql' => [
        '...'
    ],

    'testing' => [
        '...'
    ],

    'custom' => [
        'driver'    => 'mysql',
        'host'      => session()->get()->db_host,
        'database'  => session()->get()->db_database,
        'username'  => session()->get()->db_username,
        'password'  => session()->get()->db_password,
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ]

]

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

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