gpt4 book ai didi

php - Cakephp 无法即时更改数据库

转载 作者:可可西里 更新时间:2023-11-01 01:04:42 24 4
gpt4 key购买 nike

我正在尝试从一个循环中连接多个数据库,但看到 CakePHP 无法更改 database,只能更改其他信息(如用户/密码/主机)。

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

$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'

谢谢!

最佳答案

尽量不要放弃配置,只改变你需要的东西。

对于这个任务我成功地使用了

$dataSource = ConnectionManager::getDataSource('company_data');
$dataSource->config['schema'] = 'company_'.$id;

我不知道数据库切换和 mysql 作为引擎是否是一对好搭档。为此,我使用 postgresql 模式。

关于php - Cakephp 无法即时更改数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13956791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com