How to select data from 2 differenet tables using Codeigniter?

151 views Asked by At

I want to select id from 2 different tables and use the id which is present in both the tables.

seller

id | name | mobile_number | password | is_active    
1  | abc  | 987654321     | 12345678 |  0
2  | pqr  | 989898989     | 12345678 |  1
3  | lmn  | 919191991     | 12345678 |  1

where, 0 is not active and 1 is active.

tanker

id | seller_id | capacity    
1  | 1         | 14
2  | 2         | 7
3  | 2         | 3.5
4  | 3         | 3.5

where, seller_id is foreign key.

Now, I want to select all seller whose status is active i.e., is_active = 1 and whose capacity = 3.5

Here is my code.


        $data = $this->db->select('id')
                 ->from('seller')
                 ->where('is_active', 1)
                 ->get()
                 ->result();

        return $data;

    }```

```public function check_capacity($id,$capacity){

        $data=$this->db->select('seller_id',$idd)
                 ->from('tanker')
                 ->where('capacity', $capacity)
                 ->get()
                 ->result();

        return $data;
    }```

Expected Output : 

*Array
(
[0] => stdClass Object
(
[id] => 2
)

[1] => stdClass Object
(
[id] => 3
)

)*
1

There are 1 answers

5
D B On

You have to join these two tables together:

$this->db->select('*, seller.id as seller_id, tanker.id as tanker_id')
    ->from('seller')
    ->join('tanker', 'seller.id = tanker.seller_id')
    ->where('is_active', 1)
    ->where('capacity', 3.5)
    ->get()
    ->result();

Once you have this, you can play around with the parameter (e.g. choose a dynamic capacity). If you have troubles, note that you can always print the last query using:

print $this->db->last_query();