php - 在 cakephp Controller 中更改默认数据库

标签 php database cakephp

使用 CakePHP 版本:2.3.1

我有一个用于授权的默认数据库,基于此,不同的数据库用于不同的客户端(数据库名称中包含客户端名称)。

我有很多模型,它们之间有各种关系。我想使用一次调用(递归地检索所有关联的模型数据)来检索它们。

场景:

数据库

default :
clients 
[id, password, name]
[1, 'qwertycolemak', 'amazon']
[2, '5t4ck0verfl0w', 'ebay']

非默认数据库(下 2)

client_amazon
students[student_id, student_name]
course_students [student_id, course_id]
courses [course_id, course_name]

client_ebay
(same as client_amazon)

现在,假设我收到 [id:2, password:'5t4ck0verfl0w'] 的请求 我检查默认数据库(客户端)、检查密码、检索名称,在本例中为 ebay

现在,我要访问的数据库是'client_ebay'

我在 database.php 中有不同的配置对应于每个客户端。 我尝试使用

更改数据源
$this->student->setDatasource('client_ebay')
$this->course->setDatasource('client_ebay')
$this->course_student->setDatasource('client_ebay')

这适用于对模型的单个 CRUD 调用(非递归)。

但是当我使用像

这样的调用(启用递归)时
$this->student->findById(5)

数据源默认为“default”,我得到一个错误:
在数据源 default 中找不到模型 studentstudents

如何通过 Controller 动态更改所有模型(不是一个一个地)的默认数据源?

最佳答案

模型层对从Model::getDataSource()返回的对象执行所有DB操作,因此在您的 AppModel 类中覆盖该方法并在必要时在其中设置适当的数据源可能是一种选择。

这是一个(未经测试的)示例,这会将数据源设置为在 Model.globalSource 中配置的任何内容(如有必要)(以防万一设置了值)。只要可以调用 Configure::write() 就可以更改该值.

...

class AppModel extends Model
{
    ...

    public function getDataSource()
    {
        $source = Configure::read('Model.globalSource');
        if($source !== null && $source !== $this->useDbConfig)
        {
            $this->setDataSource($source);
        }

        return parent::getDataSource();
    }

    ...
}

然后在你的 Controller 中你可以做类似的事情

Configure::write('Model.globalSource', 'client_ebay');
$student = $this->Student->findById(5);

关于php - 在 cakephp Controller 中更改默认数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19492109/

相关文章:

php - 交响乐 :HOW TO Create Shared -General- (Helper) used in multiple bundles

php - 获取所有月份以及从 2 个日期开始的月份数和天数?

database - 拒绝连接到 PostgreSQL 服务器

php - 从 cocoa 应用程序中获取 MySql 数据库 - PHP 桥接

php - 无法定位与分页兼容的对象。使用 CakePHP

cakephp 使用分页和顺序

php - 限制 post sql 结果

php - Symfony2 为什么模板呈现为字符串?

database - 如果我的用户帐户没有权限,如何创建DB2 数据库?

php - cakephp hasone 和属于加入不工作