4

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. enter image description here

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?

user1149244
  • 711
  • 4
  • 10
  • 27

4 Answers4

8

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

Stack Programmer
  • 679
  • 6
  • 18
mohur
  • 1,785
  • 4
  • 16
  • 25
  • Hi Mohur, Yes I have read that earlier. But isn't it possible that when I call $this->User_model->get_by_id($user_id)->row() I can add a relation from there? Just like in YII framework, we can used "with('usermodel, usertodepartmentmodel, statusmodel')"; – user1149244 Mar 10 '13 at 16:39
3

code igniter is not a ORM framework for php...

you can not treat it like ORM frameworks(Laravel is good example for ORM frameworks).

but you can simulate that with join on query.

this work just get you the others models data and not get you those models object ...

Mahdi Youseftabar
  • 2,273
  • 1
  • 22
  • 29
0

Refer to $this->db->join(); heading in Active Record: CodeIgniter

I know codeigniter is not that good here. So I always prefer Yii over it.

Tushar
  • 166
  • 2
  • 11
  • Have you implement the model to model relationship like yii? I am looking for the same. Check what i have tried is here like yii. and will update it here.http://www.yiiframework.com/forum/index.php/topic/60061-implement-functionality-of-yii-1x-in-codeigniter/ – Yatin Mistry Dec 08 '14 at 07:07
  • I've tried also with Yii, model to model relationship. – user1149244 Oct 04 '15 at 07:46
-3

Try use this query of joining table

Select a.*,b.*
from table_one a
inner join table_two b where b.id=a.id
jalborres
  • 107
  • 6