gpt4 book ai didi

php - CakePHP 2.2.5 Controller 中的 Cakephp 切换数据库连接

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:39:06 25 4
gpt4 key购买 nike

我正在尝试从 Controller 中的两个不同数据库中获取数据

app/Controller/UsersController.php

我的数据库连接在 database.php

中声明
$default = array(
...
'database' => 'test'
...
);
$test = array(
...
'database' => 'test1'
...
);

在我的 display() 操作中:

public function display() {
$this->set('defaultUsers', $this->User->find('all'));
$this->User->schemaName = 'test1';
$this->User->cacheQueries = false;
$this->set('testUsers', $this->User->find('all'));
}

这将使我能够成功地从两个不同的来源获取数据,但是问题是这两个数据库必须有相同的密码,否则将无法工作。

我已经尝试了在这里和其他网站上找到的其他解决方案。喜欢:

  • 更改 $this->User->useDbConfig = 'test'$this->User->cacheQueries = false 仍然会给我同样的结果数据集;

  • 使用 ConnectionManager::getDataSource()setConfig()create()drop()setDataSource() 等。这些都没有用,有些甚至已经不存在了。

任何帮助将不胜感激!因为我需要为两个类似的应用程序使用相同的代码库,也就是两个数据库。

谢谢!

最佳答案

您可能需要使用“setDataSource()”来切换数据源/连接,因为这将重置模型上的“缓存”模式等;

public function display() {
$this->set('defaultUsers', $this->User->find('all'));
$this->User->setDataSource('test1');
$this->set('testUsers', $this->User->find('all'));
}

如果您需要在整个应用程序中访问两个数据库中的数据,另一种选择是创建两个 用户模型,一个使用“test”作为数据源,另一个使用“test1”作为数据源。这样您就不必一直切换数据源

例子:

class TestUser extends AppModel {
public $useTable = 'users'; // name of the database table
public $useDbConfig = 'test1'; // name of the database configuration in database.php
}

进一步说明:'$test' 数据库配置是预配置的数据库连接,用于运行 CakePHP 单元测试。您可能会考虑创建自己的数据库连接名称

关于php - CakePHP 2.2.5 Controller 中的 Cakephp 切换数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14569294/

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