How to make two and more database connections in Yii mongodbsuite?

968 views
Skip to first unread message

Vetal Polik

unread,
Oct 24, 2012, 10:16:41 AM10/24/12
to yiimong...@googlegroups.com
I write 2 DB in main.php

'components' => array(

    'mongodb' => array(
        'class'             => 'common\extentions\MongoDB',
        'connectionString'  => 'mongodb://localhost:27017/db1',
        'dbName'            => 'db1',
        'fsyncFlag'         => false,
        'persistentConnection' => 'x',
        'replicaSet'        => false,
        'safeFlag'          => true,
        'useCursor'         => false,
    ),

    'mongodb2' => array(
        'class'             => 'common\extentions\MongoDB',
        'connectionString'  => 'mongodb://localhost:27017/db2',
        'dbName'            => 'db2',
        'fsyncFlag'         => false,
        'persistentConnection' => 'x',
        'replicaSet'        => false,
        'safeFlag'          => true,
        'useCursor'         => false,
    ),

)

But how use mongodb2 in query (ex: ->findByAttributes()) i don't know. Please type some example query to mongodb2.

Vetal Polik

unread,
Oct 24, 2012, 10:19:03 AM10/24/12
to yiimong...@googlegroups.com


среда, 24 октября 2012 г., 17:16:41 UTC+3 пользователь Vetal Polik написал:
In my project all models extends \web\extensions\EMongoDocument (NOT CActiveRecord). So acticle Multiple db support in Yii not work for me.
 

Attila Nagy

unread,
Oct 24, 2012, 11:12:34 AM10/24/12
to yiimong...@googlegroups.com
Hi Vetal,

A model class can connect only to a single db. So I assume you have
different model classes for the two databases.

In this case you have two options:
- you could set the mongodb connection for every class during runtime this way:
ExampleClass::model()->setMongoDBComponent(Yii::app()->mongodb2)

- or you could override the getMongoDBComponent method in that class like this:

// make shure you check EMongoDocument::getMongoDBComponent before
doing this
public function getMongoDBComponent()
{
return Yii::app()->mongodb2;
}

The latter is a nice way if you have several models in both db's,
because then you could define two classes that extend the
EMongoDocument, and override the getMongoDBComponent method. Then
every class could extend the appropriate base class depending on which
database is it stored in.




--
Nagy Attila Gabor

Vetal Polik

unread,
Oct 25, 2012, 2:29:42 AM10/25/12
to yiimong...@googlegroups.com
Thank you very much Nagy Attila Gabor. It is work!!!
I just add 'mongodb2' => array   to  'components' => array and add to models ( ex: User) who extends EMongoDocument:


public function getMongoDBComponent()
{
    return Yii::app()->mongodb2;
}
And it is work!
Thank you again.
Reply all
Reply to author
Forward
0 new messages