Toomtarm Kung
Toomtarm Kung

Reputation: 594

Cakephp How to change database connection

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

Upvotes: 5

Views: 17793

Answers (2)

jeremyharris
jeremyharris

Reputation: 7882

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');

Upvotes: 6

mulleto
mulleto

Reputation: 364

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.

Upvotes: 10

Related Questions