Yii : multiple databases connection fails

有些话、适合烂在心里 提交于 2019-12-10 10:37:49

问题


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

well, it doesnt. :))

db is the primary database

db1 and db2 are the secondary databases

what is wrong here ?

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

回答1:


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 You need to overwrite getDbConnection() method of CActiveRecord.

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

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

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

Implement this way for both db1 & db2 database.



来源:https://stackoverflow.com/questions/12778422/yii-multiple-databases-connection-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!