Background:
For scenarios where a large company has multiple subsidiaries, we often need to configure multiple sub-database (sub-databases) to store different data records.
Configuration steps:
1. The index of the master profile main.php in the application skeleton adds a ' DB2 ' =>array (//todo the code stub) to the components.
For example:
//Application Components' Components ' =Array( ' db ' = =Array( ' connectionString ' = ' mysql:host=localhost;dbname=blog ', ' Emulateprepare 'true, ' username ' = ' root ', ' password ' = ', ' charset ' and ' UTF8 ', ' table ' Prefix ' = ' tbl_ ', ), ' db2 ' =Array( ' Class ' = ' cdbconnection ', ' connectionString ' = ' mysql:host=localhost;dbname=blog2 ', ' emulatep Repare ' =true, ' username ' = ' root ', ' password ' = ', ' charset ' and ' UTF8 ', ' table ' Prefix ' = ' tbl_ ', ), ' user ' =Array( //Enable cookie-based authentication' Allowautologin ' =true, ),
2. Create a new model class in the models directory of application, since Yii uses Yii::app ()->db this cdbconnection by default, so in order to prevent the current model class from continuing to use this default is the database connection instance, You must override a name in the model
Methods of Getdbconnection:
For example:
Public function getdbconnection () { return Yii::app (),DB2; }
3. In order to avoid some conflicting situations, please note the naming conventions of the model classes for different databases to prevent erroneous data operations from occurring.
Detailed reference: Http://www.yiiframework.com/wiki/123/multiple-database-support-in-yii
Using multiple databases in Yii