Question: **Background:**
I have an admin system, that needs to connect to and edit multiple databases. The database structures are 100% similar to each other, but the data varies.

**What I have tried:**
I'v tried to use `$this->Model->setDataSource('db_variable_here');` in the controllers to change the database on the fly. The problem with this, is that all the related data seems to still be from my default database.

**Example:**
Imagine this: `User` HABTM `Post`, if I want to get a post from a different database, and use `$this->Post->setDataSource('db_variable_here');` to achieve this, then it seems that I still get the related user from my default database, and not the same as the one I got the post from.

I'm guessing this is due to the fact that I only change the database on the Model `Post`, so it could be fixed by doing `$this->Model->setDataSource('db_variable_here');` for each related model.

**My Question:**
Is it possible to change the datasource for every model in the app on the fly?
Ex. something like: `$this->setDatasource('datasource_name')`? Or do I really have to do it manually for all the related models?

Answer: 
Just save the database that you need to use in Session/Cookie (whatever tickles your fancy), then in your AppModel's `__constructor()` if the Session variable is defined then override either `setDataSource()` or `setSource()` accordingly.

Note that IIRC Cake's Session/Cookie are not available on the Models by default (because it's not supposed to be), so you might wanna use the good ol' $\_SESSION or $\_COOKIE or you will need to load it with `App`. 

I do this to select to either use a Azure SQL database or a Rackspace MySQL database depending on the domain/URL, works as expected.
You could try making your own getDataSouce method in the AppModel.

You can see the CakePHP one here:
<https://github.com/cakephp/cakephp/blob/master/lib/Cake/Model/ConnectionManager.php>

So, in your AppModel, just make sure to accept/return the da

```
class AppModel extends Model {
    //...

    public function getDataSource() {

        // some logic here to determine which source you want
        // Maybe use Configure::write('MYSOURCE', 'other_datasource');
        // somewhere else, then just check it here.
        $source = 'default';

        $this->setDataSource($source);
        return parent::getDataSource();
    }

    //...

}

```

This should get called instead of CakePHP's 'getDataSource()', then it will run your checks to determine which connection to use, then calls CakePHP's 'getDataSouce()' to do the rest of the actual work of getting the data source.

Assuming you set a variable (like a Configure variable) that's accessible from here, you could set it once anywhere in the app, and when this runs, it will use whatever you've specified.