rafiq
rafiq

Reputation: 81

Joining on CodeIgniter tables in this query multi tables

Just want to join 1 to 3 tables in CodeIgniter, how can I do that?

In this query I have joined only one table how I can I join my 3rd, 4th table

    $this->db->select('*');
    $this->db->from('table1');
    $this->db->join('table1', 'table1.dep_id = table2.dep_id', 'table1.status= 1');
    $this->db->limit(1);
    $this->db->order_by("expiredate", "desc");
    
    return $this->db->get()->result();

my table structure as follow

Table1

t1_id
t1_name
t2_id
t3_id
t4_id

Table2

t2_id
t2_name

Table3

t3_id
t3_name

Table4

t4_id
t4_name

How can I join my 3rd and 4th

Upvotes: 3

Views: 917

Answers (2)

GautamD31
GautamD31

Reputation: 28763

Try symultaneous join like

$this->db->join('table1', 'table1.t2_id = table2.t2_id', 'table1.status= 1');

and in meanwhile you need to join any one of table1 ,tabl2 to join with table3 or 4 like

$this->db->join('table3', 'table1.t3_id = table3.t3_id');
$this->db->join('table4', 'table1.t4_id = table4.t3_id');

and moreover you need to select table like

$this->db->select('table1.*,table2.*,..');

like this way and another thing is if any columns are same for table1 and table2 then you need to select as alias like

$this->db->select('table1.id as tab1id,table2.id as tab2id');

in above table1,2 are same column names "id"

Upvotes: 1

RavatSinh Sisodiya
RavatSinh Sisodiya

Reputation: 1608

Try this I think its work

$this->db->select('table1.*,table2.t2_name,table3.t3_name,table4.t4_name');
$this->db->from('table1','table2','table3','table4');

$this->db->join('table2', 'table1.t2_id= table2.t2_id');
$this->db->join('table3', 'table1.t3_id= table3.t3_id');
$this->db->join('table4', 'table1.t4_id= table4.t4_id');

return $this->db->get()->result();

OR you can use SQL query to get result....

$this->db->query($sql)->result();

Upvotes: 5

Related Questions