Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Using multiple database connections in CakePHP model

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 3.43k
    Comment on it

    Hello Readers,

    Till now we may develop our appication with single database . Is their any ways to integrate our application with multiple databases ? . Yes we have.

    There are methods to use multiple databases for development and for production without changing anything but rewriting a function in DATABASE_CONFIG class.

    Just open your database.php file inside config folder and search this class "DATABASE_CONFIG".

    Here you can add multiple database configuration.

    class DATABASE_CONFIG {
    
        public $default = array(
            'datasource' => 'Database/Mysql',
            'persistent' => false,
            'host' => 'localhost',
            'login' => 'username',
            'password' => 'password',
            'database' => 'database1',
            'prefix' => '',
            //'encoding' => 'utf8',
        );
    
        public $test1 = array(
            'datasource' => 'Database/Mysql',
            'persistent' => false,
            'host' => 'localhost',
            'login' => 'username',
            'password' => 'password',
            'database' => 'database2',
            'prefix' => '',
            //'encoding' => 'utf8',
        );
    
        public $test2 = array(
            'datasource' => 'Database/Mysql',
            'persistent' => false,
            'host' => 'localhost',
            'login' => 'username',
            'password' => 'password',
            'database' => 'database3',
            'prefix' => '',
            //'encoding' => 'utf8',
        );
    }
    

    The default database is "public $default" , if you want to use database2 you have to initialize "public $test 1" in your Model.

    Open your UserModel.php

    class User extends AppModel {
       ...
       var $useDbConfig = 'test1';
       ...
    }
    

    or (if you want database3 to access)

    class User extends AppModel {
       ...
       var $useDbConfig = 'test2';
       ...
    }
    

    Good Luck!

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: