本文介绍了Yii : 多个数据库连接失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了 yii 文档,以下代码应该可以工作;

i read the yii docs and the following code should work;

好吧,它没有.:))

db 是主数据库

db1 和 db2 是二级数据库

db1 and db2 are the secondary databases

这里有什么问题?

该网站在线,位于 www.linkbook.co,但无法连接到任何数据库

the website is online, at www.linkbook.co, and it cant connect to any of the databases

'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!
),

推荐答案

dbYii 的预定义组件,所以默认 CActiveRecord 使使用 db 连接.因此,对于您使用 CDbConnection 类创建的其他组件,您必须在外部为它们激活连接.

db is the predefined component of Yii, so bedefault CActiveRecord makes connection using db. So for other components you have created using CDbConnection class you have to activate connection for them externally.

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

SO You need to overwrite getDbConnection() method of CActiveRecord.

扩展 CActiveRecord 以用于特定的数据库连接,例如 db1.将其另存为 Db1CActiveRecord.php 并放在 components 目录中.

Extend the CActiveRecord for specific database connection like db1.Save this as Db1CActiveRecord.php and place in components directory.

<?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.'));
        }
    }
}

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

Now you need to use Db1CActiveRecord for the model class of database db1.Like:

class Db1Model extends Db1CActiveRecord{
   ......
}

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

Implement this way for both db1 & db2 database.

这篇关于Yii : 多个数据库连接失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-26 15:51