CodeIgniter Forums
DB relations in Codeigniter - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: DB relations in Codeigniter (/showthread.php?tid=62150)



DB relations in Codeigniter - tomop - 06-13-2015

Hi guys, I'm getting desperate trying to figure out how can I access data from DB by using relations. I have successfully related two tables by setting foreign key and now I am little bit confused. Confused

Let's say I have two tables -> Cars(id, size, color) and Drivers(id, car_id, name).

IDs are primary keys, car_id is foreign key. Now, I'd like to know what color or size is George's car. Could someone tell me what is the easiest way to echo it by Codeigniter? 


RE: DB relations in Codeigniter - pdthinh - 06-13-2015

(06-13-2015, 03:29 PM)tomop Wrote: Hi guys, I'm getting desperate trying to figure out how can I access data from DB by using relations. I have successfully related two tables by setting foreign key and now I am little bit confused. Confused

Let's say I have two tables -> Cars(id, size, color) and Drivers(id, car_id, name).

IDs are primary keys, car_id is foreign key. Now, I'd like to know what color or size is George's car. Could someone tell me what is the easiest way to echo it by Codeigniter? 

You can join two tables like following:
PHP Code:
$driver_name "George";
$sql "SELECT size, color FROM cars JOIN drivers ON cars.id = drivers.car_id WHERE drivers.name = " $this->db->escape($driver_name);
$query $this->db->query($sql);
foreach (
$query->result_array() as $row) {
    echo 
$row['size'], $row['color'];

Read CI doc for more helps.


RE: DB relations in Codeigniter - Blair2004 - 06-14-2015

Actives recode has best example of db relations that you can integrate into your code. check out the documentation for more information.

here is an example
$this->db->select("*")->from("table")->join("other", "table.id = ogher.fk");