Using different databases

Currently I'm writing an extension with a widget and that is using another database. The widget (AR) models override the getDbConnection() to connect to the right database.

It seems that the last connection stays active, in other words, I have to force the main application models to use the (standard) db connection.

This makes the extension less portable, and I have to manually add the default connection to the (existing) AR models. This is probably not the right approach…

Is there a way to set the default connection back in the extension?

I am not sure if I understand you, but you can try to save the previous DB connection before you switch to a new one. And the new one is no longer used, you can switch it back with the saved copy?

The issue seems to be this: In my controller I perform a RAR findAll, cache the resultobject, and pass the resultobject to a view.

In this view I call a widget (also using AR), and this widget is using a different database (and I override the standard getDbConnection() by overriding the default in the model).

If I call the widget before the foreach() loop of the former result object, I get a CDbException, like:

The table "Company" for active record class "Company" cannot be found in the database.

If I call the widget at the end of the view, it can't find the used table of the widget.

Can it be that the used instance of CDbConnection in CActiveRecord is the same, and therefore mixes the databases?

I changed line 615 in CActiveRecord, and the problem seems to be solved now:


How did you override getDbConnection()?

Does the widget use the same AR class as your controller?

Overriding the getDbConnection in the AR model:

	public function getDbConnection()



			return self::$db;




			if(self::$db instanceof CDbConnection)



				return self::$db;



				throw new CDbException(Yii::t('yii','Active Record requires a "db2" CDbConnection application component.'));



The widget uses its own set of models.

The issue is only there when using a cached result object in the controller/view. The issue seems to be solved by changing line 615 in CActiveRecord, making sure the used db is the default db, instead of just checking on an existing connection.

Why would you store db2 into self::$db? If you use another variable, there won't be problem. Changing line 615 is not a viable solution and has many side-effects.

Okay, never thought of that to be honest… Problem solved. Thanks for pointing out.