Changes
Title
unchanged
Multiple-database support in Yii
Category
unchanged
How-tos
Yii version
unchanged
Tags
unchanged
Database
Content
changed
[...]
Once this is defined, the second database is referred to as `Yii::app()->dbadvert` rather than `Yii::app()->db` (of course, the first is still available).
But we can do much better integration than this, starting with Gii and ending with AR support.
Using Gii
---------
Gii can use multiple database connections in Yii > 1.1.11.
If you are using a previous version, Gii only knows how to use the primary database connection, so for a brief time while creating models/controllers/crud, you'll have to edit your `protected/config/main.php` file to temporarily make the advertising database the primary `db` connection:
```php[...]
Though it's possible to do this in the model definition file itself, this doesn't scale well as it would duplicate a lot of code if more than one model lives in the Advertising database. Better is to use a custom wrapper class to `CActiveRecord` where this can be centralized.
The notion of custom wrapper classes is described in <a href=[this wiki article](http://www.yiiframework.com/wiki/121/extending-common-classes-to-allow-better-customization/
">this wiki article</a>), and we'll assume that you've created a `protected/components/MyActiveRecord.php` file, and t
eachaught all of your model files to extend `MyActiveRecord` rather than `CActiveRecord`.
```php[...]
else
throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
}
}
...
```
This method is **purposely** static: the underlying cached `$dbadvert` value is, so the function may as well be be too. Now, with this helper prepared, we can edit the model itself:[...]