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”是旧的默认连接,之前由中间件更改。
谁能告诉我为什么?
谢谢
答案 0 :(得分:0)
您需要做的是清除连接。
// 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();