在Laravel中使用两个数据库

时间:2017-10-26 08:14:39

标签: php laravel

我希望像Laravel推荐的那样隐藏关键服务器访问信息,所以我已经设置了 config / database.php .env ,如下所示,但这些无法解决问题。连接每一个。哪条线错了?

Laravel版本:5.4

配置/ database.php中

'connections' => [
    'master_db' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST_MASTER', '127.0.0.1'),
        'port' => env('DB_PORT_MASTER', '3306'),
        'database' => env('DB_DATABASE_MASTER'),
        'username' => env('DB_USERNAME_MASTER'),
        'password' => env('DB_PASSWORD_MASTER'),
        'unix_socket' => env('DB_SOCKET_MASTER'),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

    'slave_db' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST_SLAVE', '192.1.0.2'),
        'port' => env('DB_PORT_SLAVE', '3306'),
        'database' => env('DB_DATABASE_SLAVE'),
        'username' => env('DB_USERNAME_SLAVE'),
        'password' => env('DB_PASSWORD_SLAVE'),
        'unix_socket' => env('DB_SOCKET_SLAVE'),
        'charset' => 'latin1',
        'collation' => 'latin1_general_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],
]

.ENV

DB_CONNECTION=master_db
DB_HOST_MASTER=127.0.0.1
DB_PORT_MASTER=3306
DB_DATABASE_MASTER=db_master
DB_USERNAME_MASTER=user_master
DB_PASSWORD_MASTER=passwordmaster

DB_CONNECTION=slave_db
DB_HOST_SLAVE=192.1.0.2
DB_PORT_SLAVE=3307
DB_DATABASE_SLAVE=db_slave
DB_USERNAME_SLAVE=user_slave
DB_PASSWORD_SLAVE=passwordslave

1 个答案:

答案 0 :(得分:1)

如果您想使用上层 config / database.php 文件样式,那么 .env 文件建议如下所示。 :)

DB_CONNECTION=master_db
DB_HOST_MASTER=127.0.0.1
DB_PORT_MASTER=3306
DB_DATABASE_MASTER=db_master
DB_USERNAME_MASTER=user_master
DB_PASSWORD_MASTER=passwordmaster

// DB_CONNECTION=slave_db <------ no needed this line
DB_HOST_SLAVE=192.1.0.2
DB_PORT_SLAVE=3307
DB_DATABASE_SLAVE=db_slave
DB_USERNAME_SLAVE=user_slave
DB_PASSWORD_SLAVE=passwordslave