CakePHP的不能即时改变数据库(Cakephp can't change databas

2019-07-12 12:50发布

我试图从数据库倍数从环路连接,但作用似乎CakePHP的不能更改database ,只有其他的相关信息(如用户名/密码/主机)。

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

谢谢!

Answer 1:

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

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

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

我不知道,如果数据库的切换和MySQL作为引擎是一双好。 我使用PostgreSQL架构用于此目的。



Answer 2:

您可以使用该模型方法的SetSource()来更改表或的setDataSource()来更改数据库的配置。



文章来源: Cakephp can't change database on-the-fly