首先,您必须在以下位置为您的数据库指定配置
.env
:
DB_CONNECTION=mysql
DB_HOST=172.17.0.1
DB_DATABASE=my_database
DB_USERNAME=username
DB_PASSWORD=password
DB_SLAVE_HOST=172.17.0.1
DB_SLAVE_DATABASE=my_database_slave
DB_SLAVE_USERNAME=username2
DB_SLAVE_PASSWORD=password2
DB_MASTER_HOST=172.17.0.1
DB_MASTER_DATABASE=my_database
DB_MASTER_USERNAME=username
DB_MASTER_PASSWORD=password
和
project.dev/config/database.php
:
'mysql_master' => [
'driver' => 'mysql',
'host' => env('DB_MASTER_HOST', 'localhost'),
'port' => env('DB_MASTER_PORT', '3306'),
'database' => env('DB_MASTER_DATABASE', 'forge'),
'username' => env('DB_MASTER_USERNAME', 'forge'),
'password' => env('DB_MASTER_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
'mysql_slave' => [
'driver' => 'mysql',
'host' => env('DB_SLAVE_HOST', 'localhost'),
'database' => env('DB_SLAVE_DATABASE', 'forge'),
'username' => env('DB_SLAVE_USERNAME', 'forge'),
'password' => env('DB_SLAVE_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
然后你可以使用setConnection
这样的方法:
public function getIndex(Product $product)
{
$this->products = $product->setConnection('mysql_slave')
->where('id' '>' 20)
->get()
...