Yii连接多个库的问题

来源:互联网 发布:代码行估算法 编辑:程序博客网 时间:2024/05/19 01:31

使用以下配置可以连接两个mysql的数据库

'db'=>array(            'connectionString' => 'mysql:host=localhost;dbname=test',            'emulatePrepare' => true,            'username' => 'root',            'password' => '123456',            'charset' => 'utf8',                        'tablePrefix'=>'HPL_'        ),        'db2'=>array(            'class'=>'CDbConnection',            'connectionString' => 'mysql:host=localhost;dbname=gmipost_dev',            'emulatePrepare' => true,            'username' => 'root',            'password' => '123456',            'charset' => 'utf8',                        'tablePrefix'=>'HPL_'        ),

注意第二个数据库配置,需要加上’class’=>’CDbConnection’。用gii生成db2的model会自动增加一个getDbConnection。

    /**     * @return \yii\db\Connection the database connection used by this AR class.     */    public static function getDb()    {        return Yii::$app->get('db2');    }

这样可以直接使用model不用处理,当然我们也可以使用Yii::app()->db2来获取数据库链接。
当然我们也可以使用这种方式来同时使用不同的两个数据库。

1 0