Reputation: 755
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?
Upvotes: 4
Views: 23353
Reputation: 1895
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
Upvotes: 8
Reputation: 2352
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 ...
Upvotes: 3
Reputation: 166
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.
Upvotes: 0
Reputation: 107
Try use this query of joining table
Select a.*,b.*
from table_one a
inner join table_two b where b.id=a.id
Upvotes: -3