Yii:多个数据库连接失败 [英] Yii : multiple databases connection fails

查看:74
本文介绍了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!
),


推荐答案

db Yii 的预定义组件,因此默认情况下 CActiveRecord 使用<$ c建立连接$ c> 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.

SO覆盖 CActiveRecord getDbConnection()方法。

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

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:多个数据库连接失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆