在yii中使用多个数据库

背景:

对于一个大公司拥有多个分公司的应用场景下,我们通常需要配置多个sub-database(子数据库)来存储不同的数据纪录。

配置步骤:

1.在application骨架里面的主配置文件main.php的索引为components中新增一个'db2'=>array(//todo the code stub.);

例如:

    // application components
    'components'=>array(
        'db'=>array(
            'connectionString' => 'mysql:host=localhost;dbname=blog',
            'emulatePrepare' => true,
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
            'tablePrefix' => 'tbl_',
        ),
        'db2'=>array(
            'class'=>'CDbConnection',
            'connectionString' => 'mysql:host=localhost;dbname=blog2',
            'emulatePrepare' => true,
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
            'tablePrefix' => 'tbl_',
        ),
        'user'=>array(
            // enable cookie-based authentication
            'allowAutoLogin'=>true,
        ),

2.在application的models目录下新建一个model类,由于Yii默认使用的是Yii::app()->db这个CDbConnection,所以为了避免当前model类继续使用这个默认是数据库连接实例,必须在model中override一个叫
getDbConnection的方法:

例如:

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

3.为了避免一些冲突的情况出现,请注意不同数据库对应的model类的命名习惯,防止出现错误的数据操作。

详细参考:http://www.yiiframework.com/wiki/123/multiple-database-support-in-yii

原文地址:https://www.cnblogs.com/bszm/p/3979215.html