在拉威尔配置飞翔上的数据库连接 [英] Configure database connections on the fly in Laravel
本文介绍了在拉威尔配置飞翔上的数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Laravel 8中,我尝试在两个场景中设置动态连接:
- 登录后,根据用户设置自定义数据库连接。
在这种情况下,登录后,在中间件中我调用了一个方法:
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;
}
这工作正常,连接工作正常。
- 我需要在作业中运行一些进程。因此,我需要访问每个用户数据库,我尝试执行相同的过程,但不断收到错误:
local.ERROR:SQLSTATE[HY000][2002]没有这样的文件或目录(SQL: 选择.为空){&Quot;Exception&Quot;:&Quot;[Object] (IlllightateDatabaseQueryException(代码:2002):SQLSTATE[HY000] [2002]没有这样的文件或目录(SQL:SELECT.为空)位于 /app/vendor/laravel/framework/src/Illuminate/Database/Connection.php:671)
有什么想法吗?我猜是在作业内部,因为它在控制台中运行,所以过程是不同的?
推荐答案
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');
这篇关于在拉威尔配置飞翔上的数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文