Quantcast
Channel: Yii Framework Forum
Viewing all articles
Browse latest Browse all 18717

Multiple Databases In One Model

$
0
0
I am trying to query multiple databases (same table, same structure, just different databases) in a model file. I am using the "mpgii" extension to create the models. Then I override the connectionId() function like this:
public function connectionId()
	{
		return array('db_1','db_2');
	}

I know I can't pass arrays to the MultiActiveRecord class so I changed the getDbConnection function to check if the returned argument is an array and if it is, get an instance for each connection like this:
$dbNameArray=$this->connectionId();
		if (is_array($dbNameArray)) {
			foreach ($dbNameArray as $dbName) {
				//var_dump($dbName);
				if(!isset(self::$db[$dbName])){
					if(Yii::app()->hasComponent($dbName) && (self::$db[$dbName]=Yii::app()->getComponent($dbName)) instanceof CDbConnection){
						self::$db[$dbName]->setActive(true);
					}else
						throw new CDbException(Yii::t('yii','Active Record requires a "'.$dbName.'" CDbConnection application component.'));
				}
			}
		} else {
			$dbName=$this->connectionId();
			//var_dump($dbName);
			if(!isset(self::$db[$dbName])){
				if(Yii::app()->hasComponent($dbName) && (self::$db[$dbName]=Yii::app()->getComponent($dbName)) instanceof CDbConnection){
					self::$db[$dbName]->setActive(true);
				}else
					throw new CDbException(Yii::t('yii','Active Record requires a "'.$dbName.'" CDbConnection application component.'));
			}
				
			return self::$db[$dbName];
		}

But when I try to access the page using the model I get this error:
Fatal error: Call to a member function getSchema() on a non-object in C:\xampp\htdocs\yii\framework\db\ar\CActiveRecord.php on line 2309
What am I doing wrong?

Viewing all articles
Browse latest Browse all 18717

Trending Articles