问题描述
我想从多个数据库连接循环,但seens CakePHP不能更改数据库
,只有其他信息(像user / pass / host)。
I am trying to connect from multiples databases from a loop, but seens CakePHP can't change database
, only others infos (like user/pass/host).
app / Config / database.php
<?php
class DATABASE_CONFIG {
[...]
public $default = array(
[..] // Where I have the companies
);
public $client = array(
[...] // Fakke settings, because I will change it on-the-fly
);
}
app / Controller / CronController.php p>
app/Controller/CronController.php
$companies = $this->Company->find('all');
foreach($companies as $company) {
$settings = array(
'datasource' => 'Database/Mysql',
'host' => $company['Company']['host'],
'login' => $company['Company']['username'],
'password' => $company['Company']['password'],
'database' => $company['Company']['database'],
);
ConnectionManager::drop('client');
$db = ConnectionManager::create('client', $settings);
try {
debug($this->MyModel->find('first'));
} catch (Exception $e) {
echo '<pre>';
echo "Exception: ", $e->getMessage(), "\n";
/*
debug($this->MyModel->getDataSource());
Outputs:
[...]
[config] => Array
(
[persistent] =>
[host] => 0.0.0.0 // CORRECT HOST
[login] => root // CORRECT LOGIN
[password] => pass // CORRECT PASSWORD
[database] => database1
[port] => 3306
[datasource] => Database/Mysql
[prefix] =>
[encoding] => utf8
)
[...]
*/
}
}
它返回第一个连接,所有其他连接,我可以从MyModel中选择任何内容,因为它是错误的。它从用户/密码/主机seens连接是确定,但是,数据库不更改,所以,因为用户没有权限选择cdatabase,我得到错误。
It return the first connection and all others I can select nothing from MyModel, because it is wrong. It seens connection from user/password/host is ok, but, database are not changed, so, because user haven't permission to select on cdatabase, I get the error.
Array
(
// First connection, connection ok, MyModel return nothing
)
// Second connection
Exception: SQLSTATE[42000]: Syntax error or access violation: 1142 SELECT command denied to user 'database_user_2'@'localhost' for table 'my_model'
// Third connection
Exception: SQLSTATE[42000]: Syntax error or access violation: 1142 SELECT command denied to user 'database_user_3'@'localhost' for table 'my_model'
// Fourth connection
Exception: SQLSTATE[42000]: Syntax error or access violation: 1142 SELECT command denied to user 'database_user_4'@'localhost' for table 'my_model'
// Fifth connection
Exception: SQLSTATE[42000]: Syntax error or access violation: 1142 SELECT command denied to user 'database_user_5'@'localhost' for table 'my_model'
$ b b
谢谢!
Thanks!
推荐答案
尝试不丢弃配置,只是改变你需要的东西。
Try not to drop config, just alter the things you need.
对于此任务,我成功使用
For this task I successfully use
$dataSource = ConnectionManager::getDataSource('company_data');
$dataSource->config['schema'] = 'company_'.$id;
我不知道数据库切换和mysql作为引擎是否良好对。我使用postgresql模式为此目的。
I don't know if database switching and mysql as engine is good pair. I use postgresql schemas for this purpose.
这篇关于Cakephp不能在运行中更改数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!