【问题标题】:Configure database connections on the fly in Laravel在 Laravel 中动态配置数据库连接
【发布时间】:2021-04-30 15:02:48
【问题描述】:

在 Laravel 8 中,我尝试在两种情况下设置动态连接:

  1. 登录后,根据用户设置自定义数据库连接。

在这种情况下,登录后,我在中间件中调用了一个方法:

public static function changeConnection($customerId)
{
    $database = Database::where('customer_id', '=', $customerId)->first();

    if (empty($database)) {
        return null;
    }

    $connectionName = 'customer';

    $config = Config::get('database.connections.' . $connectionName);
    $config = [
        'driver' => 'mysql',
        'host' => $database->database_host,
        'port' => $database->database_port,
        'database' => $database->database_name,
        'username' => $database->database_username,
        'password' => $database->database_password
    ];
    config()->set('database.connections.' . $connectionName, $config);
    DB::purge($connectionName);

    return $connectionName;
}

这很完美,连接也很完美。

  1. 我需要在作业中运行一些进程。所以我需要访问每个用户数据库,我尝试做同样的过程,但我一直收到错误:

local.ERROR: SQLSTATE[HY000] [2002] 没有这样的文件或目录(SQL: 选择...为空){“异常”:“[对象] (Illuminate\Database\QueryException(代码:2002):SQLSTATE[HY000] [2002] 没有这样的文件或目录(SQL:select ... 为空) /app/vendor/laravel/framework/src/Illuminate/Database/Connection.php:671)

有什么想法吗?我猜是在工作中,因为它在控制台中运行,所以程序不同?

【问题讨论】:

  • 您需要在使用 eloquent 选择数据库的任何地方进行更新。例如:$users = DB::connection('mysql2')->select(...);
  • @LewisSmith 我使用了不同的方式:(new Customer)->setConnection($this->customerConnection)->select...
  • 我以前没有亲自遇到过这种方法,以上方法是我如何实现您需要的解决方案。你仍然需要在配置中设置连接,然后你可以在你的模型上构建一些辅助函数来选择一个类似于你当前的方法
  • @LewisSmith 在我的情况下,连接是动态的,所以我可以设置一个没有用户、密码、数据库的连接,它应该由 config()->set(...) 更新,但它是不工作。

标签: laravel cron laravel-8 laravel-jobs


【解决方案1】:

Laravel one domain, multiple database detected by Session

几年前我也遇到过同样的问题,这是我的解决方案,如果您需要即时切换连接:

config(
[
    'database.connections.tenant' => 
    [
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'port'      => 3306,
        'database'  => 'the_database_name',
        'username'  => env('DB_USERNAME'),
        'password'  => env('DB_PASSWORD'),
        'charset'   => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
    ],
]);

$data = DB::connection('tenant')->select('Your sql');

【讨论】:

    猜你喜欢
    • 2016-07-05
    • 2016-11-11
    • 2016-04-09
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 2018-08-26
    • 2018-12-07
    相关资源
    最近更新 更多