Connecting to mulitple databases with DMZ DataMapper

﹥>﹥吖頭↗ 提交于 2019-12-12 18:15:24

问题


I'm using the DMZ DataMapper ORM for CodeIgniter.

I'm sure it is possible to configure it to connect to multiple databases. I haven't found any documentation yet. Has anyone done this before?


回答1:


Thank you for your idea indi.

in 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,

);

class Your_new_class extends Datamapper {

public $db_params = 'other_database';

}




回答2:


It's easy to set db parameters dynamically. This is what I use:

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);
  }
}

Usage:

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);

That's how I do it... it seems you have to specify db_params in the construct to make it work dynamically, otherwise datamapper goes off trying to construct/resolve relationships, etc. based on existing db settings.

If your db is set, and you don't need to modify parameters at runtime, you can also create a new entry in 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',
)

(Note that my coding style above is different from standard CI for dbs.)

Then use with:

class YourModel extends DatamapperExt {
   var $db_params = 'other_database';
}



回答3:


The solution is simple:

Create another database configuration in database.php and add

var $db_params = 'name_of_other_database';

to the model.



来源:https://stackoverflow.com/questions/5448506/connecting-to-mulitple-databases-with-dmz-datamapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!