ThinkPHP6
配置 .env 文件
# 默认数据库配置 DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=default_db DB_USERNAME=root DB_PASSWORD= # 第二个数据库配置 DB2_CONNECTION=mysql DB2_HOST=127.0.0.1 DB2_PORT=3306 DB2_DATABASE=second_db DB2_USERNAME=root DB2_PASSWORD=
config/database.php配置
database.php配置文件中可以使用.env配置中的参数
return [ // 默认数据库连接配置 'default' => env('DB_CONNECTION', 'mysql'), 'connections' => [ 'mysql' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', '3306'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'unix_socket' => env('DB_SOCKET', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ], // 第二个数据库连接 'mysql2' => [ 'driver' => 'mysql', 'host' => env('DB2_HOST', '127.0.0.1'), 'port' => env('DB2_PORT', '3306'), 'database' => env('DB2_DATABASE', 'forge'), 'username' => env('DB2_USERNAME', 'forge'), 'password' => env('DB2_PASSWORD', ''), 'unix_socket' => env('DB2_SOCKET', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ], ], // 其他配置项... ];
使用多数据库连接
// 使用默认的数据库连接 $defaultData = DB::table('users')->get(); // 使用第二个数据库连接 $secondDbData = DB::connection('mysql2')->table('orders')->get();