【问题标题】:Database switch with BindModel in cakePHP在 cakePHP 中使用 BindModel 进行数据库切换
【发布时间】:2023-03-27 03:10:01
【问题描述】:

我正在开发使用多个数据库的蛋糕 PHP 应用程序。我需要从多个表中获取数据,并且我正在使用 bindModel 进行关联。但是bindModel不允许数据库切换功能,我需要访问多个数据库中的数据。如果有人做过这种类型的任务,请帮助我。

【问题讨论】:

标签: php database cakephp database-connection


【解决方案1】:

在您的 AppModel 中

class AppModel extends Model
{
  /**
   * Connects to specified database
   */
    public function setDatabase($database, $datasource = 'default')
    {
      $nds = $datasource . '_' . $database;      
      $db  = &ConnectionManager::getDataSource($datasource);

      $db->setConfig(array(
        'name'       => $nds,
        'database'   => $database,
        'persistent' => false
      ));

      if ( $ds = ConnectionManager::create($nds, $db->config) ) {
        $this->useDbConfig  = $nds;
        $this->cacheQueries = false;
        return true;
      }

      return false;
    }
}

您可以在控制器中使用

class CarsController extends AppController
{
  public function user()
  {
    $this->User->setDatabase('testdb1');
    $cars = $this->User->find('all');
    $this->set('User', $User);
  }

  public function client()
  {
    $this->Client->setDatabase('testdb2');
    $cars = $this->User->find('all');
    $this->set('Client', $Client);
  }

}

【讨论】:

  • 我已经在使用这个配置但是我需要在使用 bindModel 函数时切换数据库。如果我在代码中编写简单的查询并切换数据库,那么这对我有用,但如果我需要 bindModel,那么它就不起作用。我想现在你有我的问题了
猜你喜欢
  • 2012-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-22
  • 1970-01-01
相关资源
最近更新 更多