Laravel 动态切换库

在config/databases.php 中新增配置:

'xd_db' => [
    'driver' => 'mysql',
    'url' => env('XD_DATABASE_URL'),
    'host' => env('XD_DB_HOST','127.0.0.1'),
    'port' => env('XD_DB_PORT', 3306),
    'database' => env('XD_DB_DATABASE', 'forge'),
    'username' => env('XD_DB_USERNAME', 'forge'),
    'password' => env('XD_DB_PASSWORD', ''),
    'charset' => env('XD_DB_CHARSET', 'utf8mb4'),
    'collation' => env('XD_DB_COLLATION', 'utf8mb4_unicode_ci'),
    'prefix' => env('XD_DB_PREFIX', ''),
    'prefix_indexes' => true,
    'strict' => true,
    'engine' => null,
    'options' => extension_loaded('pdo_mysql') ? array_filter([
        PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
    ]) : [],
],

//这样在队列里是不会动态配置

 Config::set("database.connections.xd_db", [
    'driver' => 'mysql',
    "host" => $host,
    "database" => $database,
    "username" => $data_target->db_username,
    "password" => $data_target->db_password,
    'charset' => env('XD_DB_CHARSET', 'utf8mb4'),
    'collation' => env('XD_DB_COLLATION', 'utf8mb4_unicode_ci'),
    'prefix_indexes' => true,
    'strict' => true,
    'engine' => null,
]);

正确配置

Config::set("database.connections.xd_db", [
    'driver' => 'mysql',
    "host" => $host,
    "database" => $database,
    "username" => $data_target->db_username,
    "password" => $data_target->db_password,
    'charset' => env('XD_DB_CHARSET', 'utf8mb4'),
    'collation' => env('XD_DB_COLLATION', 'utf8mb4_unicode_ci'),
    'prefix_indexes' => true,
    'strict' => true,
    'engine' => null,
]);
DB::purge('xd_db');
DB::reconnect('xd_db');

需要加


DB::purge('xd_db');
DB::reconnect('xd_db');

重新刷新配置链接

码上有钱的博客
请先登录后发表评论
  • latest comments
  • 总共0条评论