Multiple databases in Yii: MySql + SQLite

If you need two (or more) completely different db connections in the same app (e.g, MySql + SQLite), using this method works better than trying to dynamically change the static variable CActiveRecord::db. (If you are using multiple MySql dbs you could get away with a more simple solution like that, which could even take advantage of cross-db queries, which this method won’t.)

In this example, we want to read/write press release data to SQLite for the Press model:

  • main config file:
    'components'=>array(
      ....
    	'dbpress' => array(
    		'connectionString'	=> 'sqlite:' . '/path/to/press.db',
    		'charset' => 'utf8',
    		'class' => 'CDbConnection'
    	),
  • Press model:
    class Press extends CActiveRecord
    {
    // second db support:
        private static $dbpress = null;
     
        protected static function getPressDbConnection()
        {
            if (self::$dbpress !== null)
                return self::$dbpress;
            else {
                self::$dbpress = Yii::app()->dbpress;
                    self::$dbpress->setActive(true);
                    return self::$dbpress;
            }
        }
    
        public function getDbConnection()
        {
            return self::getPressDbConnection();
        }
    //
  • that’s it!

    Leave a Reply