Code Igniter Model To Model Relationship

codeigniter, models, table-relationships

Solution

example u have `table_one` and want to join `table_two` using their id

$this->db->select('columns');
$this->db->from('table_one');
$this->db->join('table_two', 'table_two.id = table_one.id');

//then do the query

you can read this link below for more complete tutorial :

https://www.codeigniter.com/userguide2/database/active_record.html

Problem

In CI, how do you relate each other the models?I have four models right now Users, UsersDepartment, UsersToDepartment, UserStatus and I need to join those four models to be able to pick up all the data. I have this code in my controller to pick all users data from the Users Table: ``` function view($user_id){ $data['user'] = $this->User_model->get_by_id($user_id)->row(); } ``` The user_status saved in the Users Table is only the status_id so I need to connect to the UserStatus table to get the equivalent name of the users_status_id. I need to know the list of group of which the user belongs to. So I need to get it from the UsersToDepartment Table based on the Users.userid. Then get the equivalent groupname in the UsersDepartment Table. Please see my diagram to explain further. I know in the native PHP, this can be done by using join. How is that done in CI? I know with yii, you can do it this way ``` $posts=Post::model()->with( 'author.profile', 'author.posts', 'categories')->findAll(); ``` Is this possible with CI too?

Original source