Cakephp无法即时更改数据库

时间:2012-12-19 16:28:36

标签: php cakephp cakephp-2.0 cakephp-2.1 saas

我正在尝试从循环中的多个数据库连接,但是看到CakePHP不能更改database,只能更改其他信息(如user / pass / host)。

应用/配置/ 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'

谢谢!

2 个答案:

答案 0 :(得分:2)

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

对于此任务,我成功使用

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

我不知道数据库切换和mysql作为引擎是不是很好。我为此目的使用postgresql模式。

答案 1 :(得分:2)

您可以使用模型方法setSource()更改表格,或使用setDataSource()更改数据库配置。