开发者

Codeigniter database connect to multiple databases in model

To bridge the gap between an older system and CodeIgniter, I have extended CI_Model in CI 2. Here's my constructor:

public function __construct ($pkname='', $tablename='')
{    
    parent::__construct ();
    $this->conf['pkname']   = $pkname;    //Name of auto-incremented Primary Key
    $this->conf['tablename']= $tablename; //Corresponding table in database

    $this->DBR = $this->load->database('read', TRUE);
    $thi开发者_开发知识库s->DBW = $this->load->database('write', TRUE);
    // echo $this->DBR->conn_id
    // echo $this->DBW->conn_id
}

If I uncomment the two lines echoing the conn_id, they are different each time. Shouldn't it be re-using the connection information? I'd think this means that I would be hitting the same Resource #ID each time. I have pconnect=TRUE for both.

Resource id #24
Resource id #25
... snip ...
Resource id #127
Resource id #128

I'm in dev so it's not a big issue but I don't want to go to production with it connecting separately for each model. Thanks.


The db_manager class in this forum post solved the problem:

http://codeigniter.com/forums/viewthread/157298/

I autoload the db_manager library then use this in my My_Model class that extends CI_Model

if (!$dbh = $this->db_manager->get_connection($type))
{
    // throw exceptions etc
}


$r = mysql_query ($query, $dbh->conn_id);

I'm using mysql_query right now because I'm converting from a different system and don't want to rewrite all the models right now. Otherwise you could use the CI Active class stuff.

Works well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜