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.


Tested with Yii 1.1.5, should work in 1.1.*


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
      'generatorPaths' =>array('ext.mpgii'),//this line does the trick
   //your other modules
    //your main database connection
    //another database connection
    //1 more database connection
    //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


forum / suport

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


show all

Related Extensions