问题描述
|
我正在将DMZ DataMapper ORM用于CodeIgniter。
我确定可以将其配置为连接到多个数据库。我尚未找到任何文档。有人做过吗?
解决方法
谢谢您的创意。
在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扩展了Datamapper {
public $db_params = \'other_database\';
}
, 动态设置数据库参数很容易。这就是我用的:
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\',)
(请注意,我上面的编码风格与数据库的标准CI不同。)
然后使用:
class YourModel extends DatamapperExt {
var $db_params = \'other_database\';
}
, 解决方案很简单:
在database.php中创建另一个数据库配置并添加
var $db_params = \'name_of_other_database\';
到模型。