Take this site as an example. we configure a primary database to connect to mysql for information management, and we configure another sqlite for the plug-in to use.
Take this site as an example. we configure a primary database to connect to mysql for information management, and we configure another sqlite for the plug-in to use.
First, configure config/main. php and add the following configuration to components:
1. mysql
?
| 1234567 |
'DB' => array ('ononstring' => 'MySQL: host = 127.0.0.1; dbname = dbname', 'emulateprepare' => true, 'username' => 'root ', 'password' => '000000', 'charset' => 'utf8 ',), |
In this way, we have connected to a database. we can use Yii: app ()-> db to ask the database instance in imitation.
2. sqlite
?
| 1234 |
'Db2 '=> array ('class' => 'cdbconnection', 'ononstring' => 'sqlite :'. dirname (_ FILE __). '/.. /data/yii. db ',), |
In this way, we can call this instance through Yii: app ()-> db2
3. The following describes how to configure the model and switch the database. because Yii calls the database by default, the db2 call method is described below.
Set the following attributes in model
?
| 1 |
Protected $ dbString = 'db2 '; |
Add the following method
?
| 1234567891011121314151617 |
PublicfunctiongetDbConnection () {if (self: $ db! = Null) returnself: $ db; else {$ dbString = $ this-> dbString; self: $ db = Yii: app ()-> $ dbString; if (self ::$ dbinstanceofCDbConnection) {self ::$ db-> setActive (true); returnself ::$ db;} else thrownewCDbException (Yii: t ('yii ', '... '));}} |
In this way, the model is configured and the db2 instance will be called.
Done!
Original content. For more information, see the source!