繁体   English   中英

在控制器 CakePHP 的同一个函数中使用两个数据库

[英]use two databases in a same function in controller CakePHP

我正在用 CakePHP 开发一个应用程序。 我需要在同一个控制器中具有相同功能的两个数据库。 在发票中,我需要在发票表中添加数据,但需要学生列表从另一个具有学生表的数据库中显示。

   public function add() {
        if ($this->request->is('post')) {
            $this->Invoice->create();           
            $this->request->data['Invoice']['created_by'] = $this->Auth->user('id');
            if ($this->Invoice->save($this->request->data)) {
                $this->Session->setFlash(__('The Invoice has been saved.'), 'default', array('class' => 'alert alert-success'));    
            }
                return $this->redirect(array('action' => 'view',$Invoice_id));
            }
        // fetch students from different database.
        $this->loadModel('Student');
        $users = $this->Student->find('list',array('fields'=>array('Student.id','Student.name')));
}

我正在使用公共 $useDbConfig = 'fees'; 作为第二个数据库配置,但无法获取相同功能的数据。 请帮忙。

<?php
class DATABASE_CONFIG {

    public $default = array(
        'datasource' => 'Database/Mysql',
        'persistent' => false,
        'host' => 'localhost',
        'login' => 'root',
        'password' => 'admin',
        'database' => 'inventory',
        'prefix' => '',
        //'encoding' => 'utf8',
    );
    // fetch students from fees controller.
    public $fees = array(
        'datasource' => 'Database/Mysql',
        'persistent' => false,
        'host' => 'localhost',
        'login' => 'root',
        'password' => 'admin',
        'database' => 'fees',
        'prefix' => '',
        //'encoding' => 'utf8',
    );
}

您需要声明您的Students模型将使用不同的数据库源。 你是说你使用了public $useDbConfig = 'fees'; 没有提及您在哪个模型中使用了此属性。

检查此链接

然后我们可以通过添加如下内容在我们的 app/Config/database.php 文件中配置数据源:

public $faraway = array( 'datasource' => 'FarAwaySource', 'apiKey' => '1234abcd', );

然后在我们的模型中使用数据库配置,如下所示:

class MyModel extends AppModel { public $useDbConfig = 'faraway'; }

所以fees看起来像一些应该在发票模型上使用的数据库:

class Invoice extends AppModel {
    public $useDbConfig = 'fees'; 
}

Students模型最有可能保留在默认数据库中

class Students extends AppModel {
    public $useDbConfig = 'default';  // This line is optional. Even if you don't write this line your model will load data from the default database.
}

也许数据库是相反的,但我认为你明白了。

您仍然可以通过执行以下操作从控制器内部配置模型的数据库源:

public function add() {
    ...
    $this->Student->useDbConfig = 'fees'
    ...
}

或最可取

public function add() {
    ...
    $this->Student->setDataSource('default')
    ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM