Laravel 动态更改连接
Posted
技术标签:
【中文标题】Laravel 动态更改连接【英文标题】:Laravel Change Connection Dynamically 【发布时间】:2017-07-01 02:00:42 【问题描述】:如何更改 laravel 的连接表单控制器,但存储在数据库中的连接信息,如数据库管理器,我的示例:
我的数据库中有一个数据库信息:
id, driver, database_name, username, password, host
所以在我的控制器上只需调用:
$connection = Database::find( 1 );
$users = new Users();
$users->setConnection( [
'driver' => $connection->driver,
'host' => $connection->host,
'username' => $connection->username,
'password' => $connection->password
] );
$users = $users->get();
【问题讨论】:
【参考方案1】:我会在这里找一个帮手。让我们在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');
现在我们在控制器的某个地方尝试
use App\Helpers\DatabaseConnection;
...
$params = Database::find( 1 );
$connection = DatabaseConnection::setConnection($params);
$users = $connection->select(...);
注意:未经测试。我希望它有效或只是指导您
更多信息:
使用多数据库:https://laravel.com/docs/5.3/database#read-and-write-connections
即时设置配置:https://laravel.com/docs/5.3/configuration#accessing-configuration-values
【讨论】:
是的,这是有效的,谢谢,这就是我要找的。span> 如何选择表名? 我想象没有这个解决方案的生活。做得好。谢谢。救生员。【参考方案2】:谢谢,EddyTheDove,我正在使用您的解决方案,这很棒:) 只是为了知道如何选择表名,我正在输入这个
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');
现在我们在控制器的某个地方尝试
使用 App\Helpers\DatabaseConnection; ...
$params['connection_name'] = 'onthefly';
$params['dbname'] ='dbname';
$params['driver'] = 'mysql';
$params['host'] = 'localhost';
$params['username'] = 'root';
$params['password'] = '';
$params['port'] = 3306;
$connection = DatabaseConnection::setConnection($params);
$getTableData = $connection->table('table_name')->where("column_name",'=','matchCondition')->get();
【讨论】:
以上是关于Laravel 动态更改连接的主要内容,如果未能解决你的问题,请参考以下文章