Dynamically created datasource not being passed to associated models in CakePHP

六月ゝ 毕业季﹏ 提交于 2019-12-04 12:58:07

Here is some code which will pass the setDatasource() call to associated models, if you want only the Car model to pass through its datasource put this code in the Car model, if you want all models to pass through, put it in AppModel.php

public function setDatasource($datasource = null) {
    foreach (array_keys($this->getAssociated()) as $modelName) {
        $this->{$modelName}->setDatasource($datasource);
    }
    parent::setDatasource($datasource);
}

To answer your comment, I would add public $dynamicDb = false in AppModel.php, meaning false would be the default value for this variable, then in your models override it by adding public $dynamicDb = true, then change the above function to:

public function setDatasource($datasource = null) {
    foreach (array_keys($this->getAssociated()) as $modelName) {
        if ($this->{$modelName}->dynamicDb === true) {
            $this->{$modelName}->setDatasource($datasource);
        }
    }
    parent::setDatasource($datasource);
}

(I haven't tested this amended function as I'm not on my dev PC right now, but its a fairly simple change and it should work)

To check if a datasource already exists before you create one, I can see two possible methods, one is by calling ConnectionManager::getDatasource($schemaName) and catching the exception if the datasource does not exist, or call ConnectionManager::sourceList() and check if your $schemaName is in the returned array, here's an implementation of the first option:

$schemaName = $this->Session->read('User.schema'); 
try {
    ConnectionManager::getDatasource($schemaName)
} catch (MissingDatasourceException $e) {
    $config = ConnectionManager::getDataSource('default')->config;
    $config['database'] = $schemaName;
    ConnectionManager::create($schemaName, $config);
}

and the second option:

$datasources = ConnectionManager::sourceList();
$schemaName = $this->Session->read('User.schema'); 
if (!in_array($schemaName, $datasources)) {
    $config = ConnectionManager::getDataSource('default')->config;
    $config['database'] = $schemaName;
    ConnectionManager::create($schemaName, $config);
}

Hope this helps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!