Laravel 多数据库配置及查询操作

laravel文档好像没有写得很详细

https://docs.golaravel.com/docs/5.3/database/

Using Multiple Database Connections
When using multiple connections, you may access each connection via the connection method on the DB facade.
The name passed to the connection method should correspond to one of the connections listed in your config/database.php configuration file: $users = DB::connection('foo')->select(...);
You may also access the raw, underlying PDO instance using the getPdo method on a connection instance: $pdo = DB::connection()->getPdo();

步骤:

1、/app/config/database.php 配置需要连接的数据库

    'connections' => [

        'sqlite' => [
'driver' => 'sqlite',
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
], 'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', ''),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
//新增01
'mysql_01' => [
'driver' => 'mysql',
'host' => env('DB_HOST_01', 'localhost'),
'port' => env('DB_PORT_01', ''),
'database' => env('DB_DATABASE_01', 'forge'),
'username' => env('DB_USERNAME_01', 'forge'),
'password' => env('DB_PASSWORD_01', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
     //新增02
'mysql_02' => [
'driver' => 'mysql',
'host' => env('DB_HOST_02', 'localhost'),
'port' => env('DB_PORT_02', ''),
'database' => env('DB_DATABASE_02', 'forge'),
'username' => env('DB_USERNAME_02', 'forge'),
'password' => env('DB_PASSWORD_02', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],

2、在.env文件 配置数据库名称、数据账号密码

第一个为默认数据库,后面两个为需要连接查询的数据名称

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=
DB_DATABASE=dataName
DB_USERNAME=root
DB_PASSWORD= DB_HOST_01=127.0.0.1
DB_PORT_01=
DB_DATABASE_01=dataName01
DB_USERNAME_01=root
DB_PASSWORD_01= DB_HOST_02=127.0.0.1
DB_PORT_02=
DB_DATABASE_02=dataName02
DB_USERNAME_02=root
DB_PASSWORD_02=

3、在Model中进行相关操作

// connection: mysql_01  database: dataName01
$datas01 = \DB::connection('mysql_01')->table('tableName')->select('...')->first();
// connection: mysql_02 database: dataName02
$datas02 = \DB::connection('mysql_02')->table('tableName')->
select('...')->first();
上一篇:【树莓派】【转】树莓派3装Android 6.0,支持Wi-Fi和蓝牙


下一篇:Laravel框架中的event事件操作