multiactiverecord Using multiple databases connections in models and gii

  1. Requirements
  2. Usage
  3. Resources

In need of use multiple databases in my models and after reading the tutorial using mutiple database connections I wrote this code and I'm here sharing with you

It comes with a Gii model generator that accepts multiple databases and will simplify things for you.

Requirements

Tested with Yii 1.1.5, should work in 1.1.*

Usage

To use it put the MultiActiveRecord under your application.components directory or any other imported folder, and the mpgii folder under your extensions folder

Your models must extend "MultiActiveRecord", like:

class myModel extends MultiActiveRecord{}

My mainly need was to find a way to set up a database for certain models, for example, the model "Pages" must connect to "database1" and the model "Sites" must connect to "database2" Using the code here described you can do it this way:

//myModel extends MultiActiveRecord like described above
class Pages extends myModel{
        //overwrite the connection id function that returns by default 'db'
        //the following code is generated automatically with MP-Gii
        function connectionId(){
            return 'db_system';
        }
}

To set up the code to connect to the databases : in your main config file ( usually configs/main.php)

return array(
//to use gii extension component that comes included in the extension do the following
'modules'=>array(
  'gii'=>array(
      'class'=>'system.gii.GiiModule',
      'password'=>'myPassword',
      'generatorPaths' =>array('ext.mpgii'),//this line does the trick
   ),
   //your other modules
),
//...
'components'=>array(
    //your main database connection
   'db'=>array('...'),
    //another database connection
   'db_system'=>array(
        'class'=>'CDbConnection',//!important
        'connectionString'=>'mysql:host=localhost;dbname=db_system',
        'username'=>'myUsername',
        'password'=>'myPassword',
    ),
    //1 more database connection
   'db_user'=>array(
        'class'=>'CDbConnection',//!important
        'connectionString'=>'mysql:host=localhost;dbname=db_user',
        'username'=>'myUsername',
        'password'=>'myPassword',
    ),
    //your other components
),

);

The model will use the database connection specified in the method connectionId and declared in your application components

and there you go, now just set up as many databases you want and define it in you models like exemplified above

Here is a screenshot of it: mar gii

hope it helps you

Resources

forum / suport

15 1
20 followers
1 825 downloads
Yii Version: 1.1
License: BSD-2-Clause
Category: Database
Developed by: Gustavo
Created on: Dec 20, 2010
Last updated: 7 years ago

Downloads

show all

Related Extensions