saurabh Suman
saurabh Suman

Reputation: 31

Is it possible to run a JOIN query using multiple database connections using CodeIgniter?

Is it possible to join multiple tables from different databases using CodeIgniter's active record utilty?

I understand that I have to create two separate database group in database.php and load them manually inside the model:

$this->DB1= $this->load->database('somename1', TRUE);
$this->DB2= $this->load->database('somename2', TRUE);

However, I don't know how to use them join multiple tables from two separate databases.

How can I accomplish this?

Upvotes: 3

Views: 1064

Answers (1)

anon
anon

Reputation:

As far as I know, there is no way to do this using multiple database instances (i.e. your $DB1 and $DB2 variables).

However, if you have a user that has access to both databases, you can prefix your table names with the their database names, and it will work (at least with MySQL - I haven't tested anything else). For example, this code:

$this->load->database('first');
$this->db->select('*')->from('users');
$this->db->join('test.hometowns', 'users.id = second.hometowns.user');
$query = $this->db->get();

Will successfully run this query, returning the expected results:

SELECT * 
FROM (`users`) 
JOIN `second`.`hometowns` ON `users`.`id` = `second`.`hometowns`.`user`;

Again, I've only tested this with MySQL, and other databases may have constraints regarding crossing database boundaries. It also requires the user account to actually have permissions to read both databases/tables.

Upvotes: 1

Related Questions