【问题标题】:Change default connection dynamically动态更改默认连接
【发布时间】:2020-03-29 15:20:55
【问题描述】:

我在 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”是中间件更改之前的旧默认连接。

谁能告诉我为什么?

谢谢

【问题讨论】:

  • 我认为是因为路由模型绑定在中间件之前使用了默认的dB
  • 可能是DB::purge('mysql');?
  • 我试过了,但是不行。我解决了 RouteServiceProvider 中更改的数据库连接

标签: php mysql database laravel connection


【解决方案1】:

您需要做的是清除连接。

// 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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    • 2015-01-09
    • 2017-07-01
    • 2021-12-24
    • 2013-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多