我正在尝试通过扩展CI_Model并根据数据库是否已定义设置正确的数据库来向我的应用程序添加单独的报告数据库。出于性能原因,报告数据库将是常规数据库的复制版本。
这是正确的方法吗?
在application / core / MY_Model中:
<?php
class MY_Model extends CI_Model
{
function __construct()
{
parent::__construct();
include APPPATH.'config/database.php';
//If we have a reporting database load it and use it for all reporting functions
if (isset($db['reports']))
{
$this->report_db = $this->load->database('reports', TRUE);
}
else
{
$this->report_db = $this->load->database('default', TRUE);
}
}
}
?>
答案 0 :(得分:1)
您可以在代码中使用这两个数据库。您必须在config/database.php
<强> database.php中强>
$active_group = 'default';
$active_record = TRUE;
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'username';
$db['default']['password'] = 'password';
$db['default']['database'] = 'database1';
$db['default']['dbdriver'] = 'mysqli';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;
$db['reports']['hostname'] = 'localhost';
$db['reports']['username'] = 'username';
$db['reports']['password'] = 'password';
$db['reports']['database'] = 'database2';
$db['reports']['dbdriver'] = 'mysqli';
$db['reports']['dbprefix'] = '';
$db['reports']['pconnect'] = TRUE;
$db['reports']['db_debug'] = TRUE;
$db['reports']['cache_on'] = FALSE;
$db['reports']['cachedir'] = '';
$db['reports']['char_set'] = 'utf8';
$db['reports']['dbcollat'] = 'utf8_general_ci';
$db['reports']['swap_pre'] = '';
$db['reports']['autoinit'] = TRUE;
$db['reports']['stricton'] = FALSE;
<强> reports_model.php 强>
<?php
class Reports_model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->db_reports = $this->load->database('reports', TRUE);
}
public function reports_list()
{
$this->db_reports->get('some_table');
}
}
<强> other_model.php 强>
<?php
class Other_model extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function xyz()
{
$this->db->get('some_table');
}
}
<强>解释强>
由于您已将default
定义为有效群组,因此无论您在database
中定义了哪些default group
,都可以在模型中使用以下内容 -
$this->db->get('some_table'); // as we defined normally
你还有其他数据库,你可以拥有另一组数据库。我们在reports group
中定义了它们。所以我们在_reports
之后添加了额外的db
-
$this->db_reports->get('some_table');