我阅读了yii文档,下面的代码应该可以工作;
嗯,没有。:))
数据库是主数据库
db1和db2是辅助数据库
这里怎么了?
网站是在线的,位于www.linkbook.co
,无法连接到任何数据库
'db' => array(
'connectionString' => 'mysql:host=localhost;dbname=linkbookco',
'emulatePrepare' => true,
'username' => 'user',
'password' => 'password',
'charset' => 'utf8',
'tablePrefix' => '',
),
'db1' => array(
'connectionString' => 'mysql:host=localhost;dbname=linkbookco1',
'username' => 'user',
'password' => 'password',
'charset' => 'utf8',
'tablePrefix' => '',
'class' => 'CDbConnection' // DO NOT FORGET THIS!
),
'db2' => array(
'connectionString' => 'mysql:host=localhost;dbname=linkbookco2',
'username' => 'user',
'password' => 'password',
'charset' => 'utf8',
'tablePrefix' => '',
'class' => 'CDbConnection' // DO NOT FORGET THIS!
),
最佳答案
db
是Yii
的预定义组件,因此bedefaultCActiveRecord
使用db
建立连接。因此,对于使用CDbConnection
类创建的其他组件,必须在外部激活它们的连接。
所以您需要覆盖getDbConnection()
的CActiveRecord
方法。
为特定的数据库连接扩展CActiveRecord
,如db1
。
将其另存为Db1CActiveRecord.php
并放入components目录。
<?php
/**
*
* Used for db1 database connection
*
*/
class Db1CActiveRecord extends CActiveRecord {
private static $db1 = null;
public function getDbConnection()
{
if (self::$db1 !== null)
return self::$db1;
else
{
self::$db1 = Yii::app()->db1;
if (self::$db1 instanceof CDbConnection)
{
self::$db1->setActive(true);
return self::$db1;
}
else
throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
}
}
}
现在需要对database
Db1CActiveRecord
的model类使用db1
。比如:
class Db1Model extends Db1CActiveRecord{
......
}
以这种方式实现db1和db2数据库。