Yii:多个数据库连接失败

Ion*_*ian 2 database multiple-databases yii

我阅读了yii文档,以下代码应该有效;

好吧,它没有.:))

db是主数据库

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!
),
Run Code Online (Sandbox Code Playgroud)

Onk*_*nwa 6

db是预定义的组件Yii,因此bedefault CActiveRecord使用连接db.因此,对于使用CDbConnection类创建的其他组件,您必须在外部激活它们的连接.

所以你需要覆盖getDbConnection()方法CActiveRecord.

扩展CActiveRecord特定的数据库连接,如db1.将其另存为Db1CActiveRecord.php并放置在组件目录中.

<?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.'));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在您需要使用Db1CActiveRecord数据库的模型类db1.喜欢:

class Db1Model extends Db1CActiveRecord{
   ......
}
Run Code Online (Sandbox Code Playgroud)

为db1和db2数据库实现这种方式.