Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp How to change database connection

Tags:

cakephp

I have 2 controllers, ContentController for general user and ManageController for administrator. I need to change the connection from default to admin and I have this code in my database.php

class DATABASE_CONFIG {

    public $default = array(
        'datasource' => 'Database/Mysql',
        'persistent' => false,
        'host' => 'localhost',
        'login' => 'user',
        'password' => '',
        'database' => 'ComputerScience',
        'prefix' => '',
        'encoding' => 'utf8',
    );

    public $admin = array(
        'datasource' => 'Database/Mysql',
        'persistent' => false,
        'host' => 'localhost',
        'login' => 'admin',
        'password' => '',
        'database' => 'ComputerScience',
        'prefix' => '',
        'encoding' => 'utf8',
    );
}

Thank you

like image 226
Toomtarm Kung Avatar asked Oct 28 '12 15:10

Toomtarm Kung


2 Answers

So, inside your Model, you would use the useDbConfig Attribute:

class Example extends AppModel {
    public $useDbConfig = 'admin';
}

Inside your Controller, simply use:

$this->ModelName->useDbConfig = 'admin';

Thats all.

like image 192
mulleto Avatar answered Oct 18 '22 08:10

mulleto


I would use Model::setDataSource() rather than just setting the database config var. This is because there are other possible changes that come with changing the datasource:

$this->Model->setDataSource('admin');
like image 20
jeremyharris Avatar answered Oct 18 '22 08:10

jeremyharris