Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Joins in Codeigniter

I'm new to building databases and I'm trying to do a JOIN based on a having three database tables.

Table A = ID, Name, etc
Table B = ID, Name, etc
Table C = ID, TableAId, TableBId

What I can't figure out is using active record how to make this selection. I'm trying to make as few requests as possible, but am getting stumped on how it should all be written without doing three separate calls.

like image 268
Seth Avatar asked Feb 06 '11 22:02

Seth


3 Answers

$this->db->select('*');
$this->db->from('TableA AS A');// I use aliasing make joins easier
$this->db->join('TableC AS C', 'A.ID = C.TableAId', 'INNER');
$this->db->join('TableB AS B', 'B.ID = C.TableBId', 'INNER');
$result = $this->db->get();

The join function works like this: join('TableName', 'ON condition', 'Type of join');

The equivilent sql:

SELECT *
FROM TableA AS A
    INNER JOIN TableC AS C
    ON C.TableAId = A.ID
    INNER JOIN TableB AS B
    ON B.ID = C.ID

I found that writing the SQL first, testing it, then converting to the active record style minimizes error.

like image 63
Michael Ozeryansky Avatar answered Oct 01 '22 22:10

Michael Ozeryansky


$this->db->select('*');
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');
$this->db->join('authors', 'authors.id = comments.author_id');

hopefully you get my example.

Just add another $this->db->join();

For complex queries you might be better off looking at an ORM such as doctrine

like image 42
Ross Avatar answered Oct 02 '22 00:10

Ross


$this->db->select('*');

$this->db->from('table1');

$this->db->join('table2','table1.id=table2.id'); 

$this->db->join('table3','table2.id=table3.id');

$this->db->join('table4','table3.id=table4.id'); 

$this->db->join('table5','table5.id=table4.id');

$this->db->where('table5.id',$this->session->userdata('id'));//getting value from session and match the id of table5 and then show data

$data=$this->db->get()->result();//all data store in $data variable
like image 35
Faisal Avatar answered Oct 01 '22 22:10

Faisal