使用 codeIgniter 查询多个数据库

Queries on multiple database with codeIgniter

我有 2 个数据库,我想对这 2 个数据库进行查询,例如

SELECT base1.table1.item1 FROM base1.table1 INNER JOIN base2.table3 ON base2.table3.item2 = base1.table1.item2 WHERE base2.table3.item4 = 'toto';

如何使用 codeIgniter 进行此查询? 我已经在 CodeIgniter 中配置了 database.php 和 2 个数据库。

谢谢。

You can setup 2 database in config/database.php file

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
'dsn'   => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'first_db',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);

//set second db configuration 
$db['otherdb'] = array(
'dsn'   => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'second_db',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE

);

When you want use default database means master database

// use master dataabse
$users = $this->db->get('users');

// connect to secondary database
 $otherdb = $this->load->database('otherdb', TRUE);
 $data = $otherdb->get('table_name');

if your first db name is base1 and second is base2

$this->db->select('table1.item1 FROM table1');
                 $this->db->from('table1');
                 $this->db->join('base2.table3', 'base2.table3.item2 =table1.item2');
$this->where('base2.table3.item4','toto')
$query = $this->db->get();