I’m about to embark on an application that will use models that reference different databases. If anyone else has some suggestions on how to do this cleanly in Yii I would be very appreciative. Also, I think it is a topic that should be covered in the Yii documentation.
Read this page to configure a database connection.
The default database component is ‘db’, but you can configure different databases by copying that code to a component named ‘db2’ (which may hold your beta table).
in your beta model override the getDbConnection() method to return the ‘db2’ component.
/* Post table */
DROP TABLE IF EXISTS `post`;
CREATE TABLE IF NOT EXISTS `post` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`title` VARCHAR(255) NOT NULL,
`text` TEXT NOT NULL,
PRIMARY KEY (`id`)
);
/* Comment table */
DROP TABLE IF EXISTS `comment`;
CREATE TABLE IF NOT EXISTS `comment` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`text` TEXT NOT NULL,
`postId` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id`)
);
Post model is a standard one. Comment model looks like this:
class Comment extends CActiveRecord {
//…
public function getDbConnection(){
return Yii::app()->db2;
}
public function tableName(){
return 'db2.comment';
}
//…
}