我想根据域切换数据库,从另一个数据库中选择凭据,但我无法切换..
应用控制器.php
// Select username, password and database based on domain
$this->Company->find('first', [...]);
if ($company) {
// Connect to second database, droping connection from first.
$dataSource = ConnectionManager::getDataSource('default');
$dataSource->config['login'] = $company['Company']['dbuser'];
$dataSource->config['password'] = $company['Company']['dbpass'];
$dataSource->config['database'] = $company['Company']['dbname'];
/**
* PROBLEM START HERE:
* Here, need to use new database settings, and, this case
* Company table does not exists, but I always get it, so,
* I think I am connected with the first and not second connection.
*/
print_r($this->Company->find('first'));
}
我该如何纠正这个?
编辑
我试过没有成功:
ConnectionManager::drop('default');
ConnectionManager::create('default', $settings);
print_r(ConnectionManager::create('default', $settings))
回报:
[... lots of things ... ]
[config] => Array
(
[persistent] =>
[host] => localhost
[login] => login
[password] => password
[database] => database
[port] => 3306
[datasource] => Database/Mysql
[prefix] =>
)
[... more things ... ]
编辑 2
现在,我可以切换数据库,但是,公司模型总是得到旧的数据库设置。
FooController.php
<?php
App::uses('AppController', 'Controller');
class FooController extends AppController {
var $uses = array('Foo', 'Company');
public function index() {
echo'<pre>';
print_r($this->Company->find('first')); // Here I get from old settings
print_r($this->Foo->find('first')); // Here I gete from new settings
echo'</pre>';
$this->layout = false;
$this->render(false);
}
}
应用控制器.php
public function beforeFilter() {
$company = ClassRegistry::init('Company')->find('first');
$settings = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => $company['Company']['dbuser'],
'password' => $company['Company']['dbpass'],
'database' => $company['Company']['dbname'],
'prefix' => ''
);
ConnectionManager::getDataSource('default')->disconnect();
ConnectionManager::drop('default');
ConnectionManager::create('default', $settings);
ConnectionManager::getDataSource('default')->connect();
}