Yii PHP框架中的多个数据库连接

时间:2015-05-08 09:01:21

标签: php yii

这是main.php文件:

        'db' => array(
            'connectionString' => 'mysql:host=MYHOST;dbname=MYDB',
            'emulatePrepare' => true,
            'username' => 'MYUSER',
            'password' => 'MYPASS',
            'charset' => 'utf8',
        ),
        'dbanother' => array(
            'connectionString' => 'mysql:host=MYHOST;dbname=MYDB2',
            'emulatePrepare' => true,
            'username' => 'MYUSER2',
            'password' => 'MYPASS2',
            'charset' => 'utf8',
            'class' => 'CDbConnection'
        ),

在组件的UserIdentity中我有这个:

 public function authenticate() {
    .........
    $loggedInUser = User::model()->find("username = :username", array("username" => $this->username));
    ......
 }

并在用户模型中,我想使用MYDB2数据库中的表用户:

    class User extends CActiveRecord {

        private $connection_db2;

        /**
         * @see db connections from config/main.php
         */
        public function __construct(){
            $this->connection_db2= Yii::app()->dbanother;
        }

        public static function model($className=__CLASS__){
            return parent::model($className);
        }

        public function tableName() {
            return Yii::app()->dbanother->users;
            // here i want to declare That i want to use the table **users**
        }
    .....
    }

目前我得到了这个:

  

属性" CDbConnection.users"没有定义。

你能帮我解决这个问题吗? THX

1 个答案:

答案 0 :(得分:0)

它更简单:)只需覆盖班级中的getDbConnection()方法:

public function getDbConnection() {
    return Yii::app()->dbanother;
}