Yii multi-database configuration explanation and CActiveRecord call

Source: Internet
Author: User
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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.