2

我正在尝试在 Codeigniter 中连接两个数据库。我遇到了这个链接Codeigniter - 多个数据库连接并根据我的要求设置数据库。现在的问题是只有默认数据库是活动的。这是代码

模型

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'

数据库.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 视为活动的,所有查询都连接到数据库 2,即使$this->db->query();用于指定查询。

4

1 回答 1

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();
}
于 2013-05-21T02:52:58.020 回答