The project is bigger, the database master or slave is not few. Using the YII framework to develop, how to set the master and slave of the database? It's actually very simple.
First, a primary database server and a number of cases from the database server, modify the configuration file config/db.php, where Slaveconfig is from the public part of the server, can also be set to slaves in the configuration of the various slave servers.
‘class‘ => ‘yii\db\Connection‘,
//Configure primary server
‘dsn‘ => ‘dsn for master server‘,
‘username‘ => ‘master‘,
‘password‘ => ‘‘,
‘charset‘ => ‘utf8‘,
'tableprefix' = > PHP ', / / the default value is empty
//Configure slave server
‘slaveConfig‘ => [
‘username‘ => ‘slave‘,
‘password‘ => ‘‘,
‘charset‘ => ‘utf8‘,
‘tablePrefix‘ => ‘php_‘,
‘attributes‘ => [
// use a smaller connection timeout
PDO::ATTR_TIMEOUT => 10,
]
]
//Configure from server group
‘slaves‘ => [
[‘dsn‘ => ‘dsn for slave server 1‘],
[‘dsn‘ => ‘dsn for slave server 2‘],
[‘dsn‘ => ‘dsn for slave server 3‘],
[‘dsn‘ => ‘dsn for slave server 4‘],
]
can also master server is also multiple that the main server configuration is the following, where the character encoding set, table prefix and other settings refer to the above.
//Configure primary server
‘masterConfig‘ => [
‘username‘ => ‘master‘,
‘password‘ => ‘‘,
‘attributes‘ => [
// use a smaller connection timeout
PDO::ATTR_TIMEOUT => 10,
]
]
//Configure primary server group
‘masters‘ => [
[‘dsn‘ => ‘dsn for master server 1‘],
[‘dsn‘ => ‘dsn for master server 2‘],
]
Well configured, so how to use it, yii this is very good, because you almost do not have to modify your code, regardless of how your code database operations using the master server configuration or from the database configuration, the framework itself has been implemented. In the default system, the Execut () function operates the main library, and other operations are from the library, such as Queryall (). And also for AR operation, because he is based on Yii:: $app->db to achieve.
More detailed information can be found in the official documentation Http://www.yiichina.com/doc/guide/2.0/db-dao
YII2 Master-Slave database settings