如何与中流幼体护照使用动态数据库连接

问题描述 投票:0回答:1

我从env文件和database.php文件中删除了数据库连接信息。然后,我根据客户端的每个请求动态设置数据库。我在主要中间件中执行此操作

$origin = $request->header('Origin');
\Config::set(['database.default' => 'mysql']);
\Config::set(['database.connections.mysql.host' => '127.0.0.1']);
\Config::set(['database.connections.mysql.database' => $origin]);
\Config::set(['database.connections.mysql.username' => 'root']);
\Config::set(['database.connections.mysql.port' => '3306']);

我的登录名没有问题,令牌已创建。但是在其他操作中,我收到401错误实际上,通行证会从env文件或database.php调用到数据库的连接信息。但是我们想通过中间件来做到这一点,或者我们可以在检查auth:api之前为其设置数据库信息。

laravel laravel-passport
1个回答
0
投票

以这种方式在中间件上完成之后。

Config::set("database.connections.mysql", [
     "driver" => "mysql",
     "host" => config('remote.server'),
     "database" => config('remote.database'),
     "username" => config('remote.user'),
     "password" => config('remote.password'),
]);
// Keep in mind that these settings are cached. 
// So when you need to use the new settings, purge the DB cache for the connection you're gonna use.
DB::purge('mysql');
// Rearrange the connection data
DB::reconnect('mysql');

您应该将此添加到将要使用的模型类中。

protected $connection = 'mysql';
© www.soinside.com 2019 - 2024. All rights reserved.