Skip to content

Yii中同时连接多个数据库

2011 七月 9
tags: ,
by 荒野无灯

0×01: 配置
在主配置文件 (main.php) 中:

1
2
3
4
5
6
7
8
9
10
11
        'db'=>array(
            'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
        ),
    'db2'=>array(
            'class'            => 'CDbConnection' ,
            'connectionString' => 'mysql:host=localhost;dbname=test',
            'emulatePrepare' => true,
            'username' => 'test',
            'password' => 'test',
            'charset' => 'utf8',
        ),

注意,第二个以后的db数组中一定要写上class参数,让Yii 知道你在定义一个数据库连接对象,不然会报错。
一旦我们这样定义以后,就可以通过Yii::app()->db2 来指向第二个数据库了。

0×02 重载 GetDbConnection() 方法
因为每个Model都是(直接或者间接地)继承自基类CActiveRecord的,因此,都包含GetDbConnection()这个方法,GetDbConnection()返回一个数据库连接对象的句柄。我们需要在模型(model)里面通过重载这个方法来返回我们需要的数据库对象。
然后,假设我们新建了一文件 : protected/components/MyActiveRecord.php ,然后在你的所有要用db2这个数据库的model里extend MyActiveRecord 而不是 CActiveRecord 。
这里我们是通过扩展Yii通用类来定义一个新的类,而不是在每个模型里面都重载 getDbConnection 方法,这样做的好处是更大程度上的代码重用,节省时间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// protected/components/MyActiveRecord.php
 
class MyActiveRecord extends CActiveRecord {

    public function getDbConnection()
    {
        if(self::$db!==null)
            return self::$db;
        else
        {
                        //这里就是我们要修改的
            self::$db=Yii::app()->getComponent('db2');
                        //self::$db=Yii::app()->db2;
            if(self::$db instanceof CDbConnection)
                return self::$db;
            else
                throw new CDbException(Yii::t('yii','Active Record requires a "db2" CDbConnection application component.'));
        }
    }
...........
}

0×03 在模型中使用
经过以上两步以后,我们就可以这样来用:

1
2
3
4
5
// protected/models/Ad.php
 
class Ad extends MyActiveRecord {
    ...
}

参考:
http://www.yiiframework.com/wiki/121/extending-common-classes-to-allow-better-customization/

http://www.yiiframework.com/wiki/78/multiple-databases-and-multiple-domains/

http://www.yiiframework.com/wiki/123/multiple-database-support-in-yii/

喜欢这篇文章吗?

请订阅本站 RSS feed填写您的邮件地址,订阅我们的精彩内容:,欢迎点击这里捐赠以支持荒野无灯转播到腾讯微博 转播到腾讯微博

作者:荒野无灯
出处:Hacklog【Hacklog】

声明: 本站遵循 署名-非商业性使用-相同方式共享 3.0 共享协议. 转载请注明转自Hacklog【荒野无灯weblog】

本文链接: http://ihacklog.com/?p=4594

One Response Post a comment
  1. 七月 9, 2011

    这个是折腾什么东东呢。

Leave a Reply

Allowed Tags - You may use these HTML tags and attributes in your comment.

<a href="" title=""> <abbr title=""> <acronym title=""> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <q cite=""> <strong>

 :wink:  :-|  :-x  :twisted:  :)  8-O  :(  :roll:  :-P  :oops:  :-o  :mrgreen:  :lol:  :idea:  :-D  :evil:  :cry:  8)  :arrow:  :-?  :?:  :!:

Note: You may use basic HTML in your comments. Your email address will not be published.

Subscribe to this comment feed via RSS

欢迎您 点击这里 订阅我的博客 o(∩_∩)o ~~~ x