php - 动态更改默认连接
问题描述
我在 Laravel 应用程序中有一个动态更改数据库连接的中间件:
public function handle($request, Closure $next)
{
Config::set('database.default', 'mysql_'.$request->segment(1));
DB::reconnect('mysql_'.$request->segment(1));
app()->setLocale($request->segment(1));
if (Auth::check() && session('locale') != $request->segment(1))
{
Auth::logout();
return redirect('login');
}
return $next($request);
}
这项工作,默认连接更改,但模型连接保持旧。
在模型的转储中,我有:
“mysql_es”是由 url 段 (/es) 更改的默认连接
“mysql_it”是中间件更改之前的旧默认连接。
谁能告诉我为什么?
谢谢
解决方案
您需要做的是清除连接。
// Purge the current database connection, thus making Laravel get the default values all over again...
DB::purge('default');
// Now set the new connection
config(['database.default' => 'mysql_it']);
// ! Reconnect and close previous connection
DB::reconnect('default');
// Ping the database.
// This will throw an exception in case the database does not exists or the connection fails
Schema::connection('default')->getConnection()->reconnect();
推荐阅读
- r - 从同一对象中调用 S4 函数
- azure-language-understanding - 如何拥有多个相同问题但答案不同的常见问题解答(KB)?
- python - 如何在 X 轴上添加水平滚动条?
- indexing - InnoDB 是否在索引中以扩展形式存储多字节字符串?
- c - 如果我们不使用 free() 分配内存会发生什么
- pandas - 如何摆脱“AttributeError:'float'对象没有属性'log2'”
- javascript - 如何使图像覆盖html中的完整部分
- reactjs - React Native Jest 语法错误:未终止的正则表达式
- sql-server - SSRS RS.exe 以错误的顺序迁移报告/数据集
- c - 在C中查找图像的内圆半径