1

I have a problem with this solution. Let mi first show you my code to better understand what i gonna to say :)

I get the code from this topic -> How to use multiple databases dynamically for one model in CakePHP

My AppModel.php

    public function setDatabase($database, $prefix = 'b2b')
{
    $nds = $prefix . '_' . $database;
    $db  = ConnectionManager::getDataSource($prefix);

    $db->setConfig(array(
        'name'       => $nds,
        'database'   => $nds,
        'persistent' => false
    ));

    if ( $ds = ConnectionManager::create($nds, $db->config) ) {
        $this->useDbConfig  = $nds;
        $this->cacheQueries = false;
        return true;
    }

    return false;
}

In database.php i have:

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

In controller i do something like this:

    $this->loadModel('User');
    if($this->isSubdomainSet()) {
        $this->User->setDatabase($this->getSubdomain());
    }
    $this->loadModel('Package');
    if($this->isSubdomainSet()) {
        $this->Package->setDatabase($this->getSubdomain());
        $packages = $this->Package->find('all');
    }

The problem is that the second model (Package) get data from default database not form the b2b base. Where is the problem? I dont know why the method setDatabase dont change the database second time.

Community
  • 1
  • 1
Tomek
  • 11
  • 2

1 Answers1

0

The database is not changed, because you changed to the same twice

$this->User->setDatabase($this->getSubdomain());

and later you do

$this->Package->setDatabase($this->getSubdomain());

So it can't be another database. I think getSubdomain() will return the same both times

CodeFox
  • 447
  • 4
  • 12
  • Yes, the 'getSubdomain()' return the same name of the database that i want to connect. But te second model did not connect to this database but it still use the default database. – Tomek Apr 24 '15 at 07:24