我试图从一个循环中连接多个数据库,但看到 CakePHP 无法更改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
);
}
应用程序/控制器/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 中选择任何内容,因为它是错误的。它看到来自用户/密码/主机的连接是好的,但是,数据库没有改变,所以,因为用户没有在 cdatabase 上选择的权限,我得到了错误。
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'
谢谢!