2

我正在为 CodeIgniter 使用 DMZ DataMapper ORM。

我确信可以将其配置为连接到多个数据库。我还没有找到任何文档。有没有人这样做过?

4

3 回答 3

2

谢谢你的想法。

在 application/config/database.php

$db['other_database'] = array(
'hostname' => 'your_host_name',
'username' => 'your_user_name',
'password' => 'your_paasword',
'database' => 'other_database_name',
'prefix' => '',
'dbdriver' => 'mysql',
'pconnect' => true,
'db_debug' => true,
'cache_on' => false,
'char_set' => 'utf8',
'cachedir' => '',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'autoinit' => FALSE,
'stricton' => FALSE,

);

类 Your_new_class 扩展 Datamapper {

public $db_params = 'other_database';

}

于 2012-10-19T03:14:42.073 回答
1

动态设置数据库参数很容易。这就是我使用的:

class DatamapperExt extends Datamapper {

  public function __construct($id, $db) {
    if ($db != null) {         
      // use these params as default - they don't change much. 
      $this->db_params = array_merge(array( 
        'dbdriver'  => 'mysql',
        'pconnect'  => true,
        'db_debug'  => true,
        'cache_on'  => false,
        'char_set'  => 'utf8',
        'cachedir'  => '',
        'dbcollat'  => 'utf8_general_ci',
      ), $db);
    parent::__construct($id);
  }
}

用法:

class YourModel extends DatamapperExt {

}

$db = array(
  'hostname'      => 'database_host',
  'username'      => 'database_username',
  'password'      => 'database_password',
  'database'      => 'database_name',
  'prefix'        => 'CI table_prefix - if any',
);

$your_model_with_diff_db = new YourModel(NULL, $db);
$model_with_id_diff_db   = new YourModel(12, $db);

我就是这样做的……看来您必须在构造中指定 db_params 以使其动态工作,否则 datamapper 会根据现有的数据库设置尝试构造/解析关系等。

如果你的db已经设置好了,运行时不需要修改参数,你也可以在config/database.php新建一个入口:

$db['other_database'] = array(  
  'hostname'      => 'database_host',
  'username'      => 'database_username',
  'password'      => 'database_password',
  'database'      => 'database_name',
  'prefix'        => 'CI table_prefix - if any',
)

(请注意,我上面的编码风格与 dbs 的标准 CI 不同。)

然后使用:

class YourModel extends DatamapperExt {
   var $db_params = 'other_database';
}
于 2011-06-14T13:28:50.237 回答
0

解决方案很简单:

在 database.php 中创建另一个数据库配置并添加

var $db_params = 'name_of_other_database';

到模型。

于 2011-03-28T16:41:29.547 回答