MYSQL|Laravel 使用多个数据库连接

1、配置.env文件

DB_CONNECTION=mysql DB_HOST=localhost DB_PORT=3306 DB_DATABASE=laravel DB_USERNAME=root DB_PASSWORD=rootDB_HOST_NEW=127.0.0.1 DB_PORT_NEW=3306 DB_DATABASE_NEW=laravel_new DB_USERNAME_NEW=root DB_PASSWORD_NEW=root

2、配置config/database.php
'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, ],'mysql_new' => [ 'driver' => 'mysql', 'host' => env('DB_HOST_NEW', '127.0.0.1'), 'port' => env('DB_PORT_NEW', '3306'), 'database' => env('DB_DATABASE_NEW', 'forge'), 'username' => env('DB_USERNAME_NEW', 'forge'), 'password' => env('DB_PASSWORD_NEW', ''), 'unix_socket' => env('DB_SOCKET_NEW', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ],

3、创建model
a、这个model将采用默认的'mysql'连接 class UserModel extends Model { // 数据库'database'中的users表 protected $table = "users"; }b、 这个model将使用mysql_new连接 class UserModel extends Model { // 数据库'dadtabase_new'中的users表 protected $connection = 'mysql_new'; protected $table = "users"; }

【MYSQL|Laravel 使用多个数据库连接】

    推荐阅读