L
L
Lomoson2015-01-21 17:22:13
MySQL
Lomoson, 2015-01-21 17:22:13

How to work with multiple bases in Yii?

I want to make such piece: at registration for the company the separate database is created. There are pros and cons to this, but this is not about that now.
I have no experience with such an architecture. Please let me know how it can be done properly.
I googled and found yiiframework.ru/doc/cookbook/ru/model.multiple.dat... but it didn't give me a complete idea how to do it.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
MniD, 2015-01-21
@MniD

Hmm, everything is described in detail there, in the configs you specify the database configurations, and in the model using getDbConnection you indicate which database the model belongs to

class Model extends CActiveRecord {
    public function getDbConnection(){
        return Yii::app()->db2; // db2 - имя базы из конфига
    }
}

Please clarify what you don't understand.

V
Vit, 2015-01-21
@fornit1917

In Yii, all work with the database goes through an instance of the CDbConnection class. You need to slip the connection to the base you need wherever you need it. How exactly to do this depends on the specifics of the application you are developing. If, for example, you can definitely determine which company the current user belongs to within one http request, and you are sure that within this http request you will not need any database other than the database of his company, then you can make a "dynamic" configuration of the component db in the application config.

E
Eugene, 2015-01-21
@Nc_Soft

everything is very simple, in the config
'components'=>array(
'dbGlobal'=>array(
)
) you
call it via Yii::app()->dbGlobal->..
when you work with a company, then most likely access to the database is stored in the global database
, you need to create a db component through createComponent with which you will work within the company

K
krypt3r, 2015-01-22
@krypt3r

Here is an example of a config from a working project that works with two databases:

'components'=>array(
     'oradb'=>array(
         'class' => 'ext.oci8Pdo.OciDbConnection',
         'connectionString' => 'oci:dbname=xxx.xxx.xxx.xxx:xxxx/dbo;charset=AMERICAN_AMERICA.cl8mswin1251',
         'username' => 'login',
         'password' => 'password',
         'enableProfiling' => TRUE,
         'enableParamLogging' => TRUE,
     ),

     'mydb'=>array(
         'class' => 'CDbConnection',
         'connectionString' => 'mysql:host=localhost;dbname=somedb',
         'username' => 'login',
         'password' => 'password',
         'charset' => 'UTF8',
     ),
…
);

Well, in the code, calls to databases go through Yii::app()->mydb or Yii::app()->oradb

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question