我正在尝试连接Codeigniter中的两个数据库。我来到这个链接Codeigniter - multiple database connections并按照我的要求设置数据库。现在问题是只有默认数据库是活动的。这是代码
模型
function __construct()
{
parent::__construct();
$this->db_2 = $this->load->database('database2', TRUE);
$this->load->database();
}
function get_details()
{
$result1 = $this->db->query("select columnname1 from tablename")->result();
$result2 = $this->db_2->query("select columnname2 from tablename")->result();
}
我收到错误,因为columnname2
仅存在于database2表中,而不存在于database1表中。
Error: Unknown column 'columnname2' in 'field list'
database.php中
$db['database2']['hostname'] = 'localhost';
$db['database2']['username'] = 'root';
$db['database2']['password'] = '';
$db['database2']['database'] = 'database2';
$db['database2']['dbdriver'] = 'mysql';
$db['database2']['dbprefix'] = '';
$db['database2']['pconnect'] = TRUE;
$db['database2']['db_debug'] = TRUE;
$db['database2']['cache_on'] = FALSE;
$db['database2']['cachedir'] = '';
$db['database2']['char_set'] = 'utf8';
$db['database2']['dbcollat'] = 'utf8_general_ci';
$db['database2']['swap_pre'] = '';
$db['database2']['autoinit'] = TRUE;
$db['database2']['stricton'] = FALSE;
$active_group = 'default';
$active_record = TRUE;
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'database1';
$db['default']['dbdriver'] = 'mysql';
$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;
更新:如果我使用以下
function __construct()
{
parent::__construct();
$this->load->database();
$this->db_2 = $this->load->database('database2', TRUE);
}
数据库2被CI视为活动状态,即使$this->db->query();
用于指定查询,所有查询也都连接到数据库2。
答案 0 :(得分:1)
在构造函数中调用两个数据库实例将导致一个覆盖另一个。最简单的方法是拆分你的功能并将它们合并在一起。
function __construct() {
$this->load->database('default', true);
}
function merge_results() {
$result_a = $this->get_result_a();
$result_b = $this->get_result_b();
return array_merge($result_a,$result_b);
}
function get_result_a() {
return $this->db->query("select columnname1 from tablename")->result();
}
function get_result_b() {
$other_db = $this->load->database('db2',true);
return $other_db->query("select columnname2 from tablename")->result();
}