作为上面的标题,我需要连接到从属数据库(出于某种原因)...
但是我找不到方法吗?
。
以下是我的数据库配置:
'mysql' => [
'read' => [
'host' => env('DB_SLAVE', '127.0.0.1'),
'port' => env('DB_SLAVE_PORT', '3306'),
'username' => env('DB_SLAVE_USERNAME', 'root'),
'password' => env('DB_SLAVE_PASSWORD', 'pwdforslave'),
],
'write' => [
'host' => env('DB_MASTER', '127.0.0.1'),
'port' => env('DB_MASTER_PORT', '3308'),
'username' => env('DB_MASTER_USERNAME', 'masteruser'),
'password' => env('DB_MASTER_PASSWORD', 'pwdformaster'),
],
'driver' => 'mysql',
'database' => 'amazingapp',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => 'aa_',
'strict' => false,
'engine' => env('DB_ENGINE', 'InnoDB'),
'unix_socket' => env('DB_SOCKET', ''),
],
。
要与从数据库进行连接,目前我在想的是DB::connection('mysql.slave');
但是它不起作用。
答案 0 :(得分:0)
您可以在DB
上进行多个.env
连接,而无需触摸database.php
这就是我连接多个数据库连接的方式
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=sample
DB_USERNAME=root
DB_PASSWORD=123456
DB_CONNECTION=mysql1
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=sample
DB_USERNAME=root
DB_PASSWORD=123456
,并且您想按protrafree
类似这样的东西
DB::connection('mysql')
或
DB::connection('mysql1')
答案 1 :(得分:-2)
您的意思是在database.php
内创建新的数据库连接条目,并通过DB::connection('mysql2')
与统计方法连接?
也许您可以检查此链接Laravel Multiple Database
。
可以尝试此配置
'mysql' => [
'read' => [
'host' => env('DB_SLAVE', '127.0.0.1'),
'port' => env('DB_SLAVE_PORT', '3306'),
'username' => env('DB_SLAVE_USERNAME', 'root'),
'password' => env('DB_SLAVE_PASSWORD', 'pwdforslave'),
],
'write' => [
'host' => env('DB_MASTER', '127.0.0.1'),
'port' => env('DB_MASTER_PORT', '3308'),
'username' => env('DB_MASTER_USERNAME', 'masteruser'),
'password' => env('DB_MASTER_PASSWORD', 'pwdformaster'),
],
'driver' => 'mysql',
'database' => 'amazingapp',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => 'aa_',
'strict' => false,
'engine' => env('DB_ENGINE', 'InnoDB'),
'unix_socket' => env('DB_SOCKET', ''),
],
'mysql_master' => [
'host' => env('DB_MASTER', '127.0.0.1'),
'port' => env('DB_MASTER_PORT', '3308'),
'username' => env('DB_MASTER_USERNAME', 'masteruser'),
'password' => env('DB_MASTER_PASSWORD', 'pwdformaster'),
'driver' => 'mysql',
'database' => 'amazingapp',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => 'aa_',
'strict' => false,
'engine' => env('DB_ENGINE', 'InnoDB'),
'unix_socket' => env('DB_SOCKET', ''),
],
'mysql_slave' => [
'host' => env('DB_SLAVE', '127.0.0.1'),
'port' => env('DB_SLAVE_PORT', '3306'),
'username' => env('DB_SLAVE_USERNAME', 'slaveuser'),
'password' => env('DB_SLAVE_PASSWORD', 'pwdforslave'),
'driver' => 'mysql',
'database' => 'amazingapp',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => 'aa_',
'strict' => false,
'engine' => env('DB_ENGINE', 'InnoDB'),
'unix_socket' => env('DB_SOCKET', ''),
],
。
因此,如果要连接到从站,只需使用DB::connection('mysql_slave');