Laravel 动态改变连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42198046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:18:56  来源:igfitidea点击:

Laravel Change Connection Dynamically

phpdatabaselaravelconnection

提问by Yudi Yohanes Septian Gotama

How to change laravel's connection form controller but the connection information stored at database like database manager, my example :

如何更改laravel的连接形式控制器但连接信息存储在数据库管理器等数据库中,我的示例:

I have a databases information on my database :

我的数据库上有一个数据库信息:

id, driver, database_name, username, password, host

so at my controller just call :

所以在我的控制器上只需调用:

$connection = Database::find( 1 );
$users = new Users();
$users->setConnection( [
    'driver' => $connection->driver,
    'host' => $connection->host,
    'username' => $connection->username,
    'password' => $connection->password
] );
$users = $users->get();

回答by EddyTheDove

I will go for a helper here. Let's create one in app/Helpers/DatabaseConnection.php.

我会去这里找个帮手。让我们在app/Helpers/DatabaseConnection.php.

namespace App\Helpers;
use Config;
use DB;

class DatabaseConnection
{
    public static function setConnection($params)
    {
        config(['database.connections.onthefly' => [
            'driver' => $params->driver,
            'host' => $params->host,
            'username' => $params->username,
            'password' => $params->password
        ]]);

        return DB::connection('onthefly');
    }
}

And now somewhere in controller we try

现在在控制器的某个地方我们尝试

use App\Helpers\DatabaseConnection;
... 

$params = Database::find( 1 );
$connection = DatabaseConnection::setConnection($params);
$users = $connection->select(...);

Note: Not tested. I hope it works or simply guide you

注:未测试。我希望它有效或只是指导你

More info:

更多信息: