代码点火器模型与模型关系

时间:2013-03-10 15:54:48

标签: codeigniter models table-relationships

在CI中,你们如何相互关联模型?我现在有四个模型用户,用户部门,用户部门,用户状态和我需要加入这四个模型才能获取所有数据。

我在控制器中有这个代码从用户表中选择所有用户数据:

function view($user_id){
                 $data['user'] = $this->User_model->get_by_id($user_id)->row();
}

用户表中保存的user_status只是status_id,因此我需要连接到UserStatus表以获取users_status_id的等效名称。我需要知道用户所属的组列表。所以我需要根据Users.userid从UsersToDepartment表中获取它。然后在UsersDepartment表中获取等效的组名。请参阅我的图表以进一步解释。 enter image description here

我知道在本机PHP中,这可以通过使用join来完成。如何在CI中完成?

我知道yii,你可以这样做

$posts=Post::model()->with(
'author.profile',
'author.posts',
'categories')->findAll();

CI也可以吗?

4 个答案:

答案 0 :(得分:7)

示例您有table_one并希望使用其ID

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

//then do the query

您可以阅读以下链接以获取更完整的教程:

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

答案 1 :(得分:3)

代码点火器不是php的ORM框架......

你不能像ORM框架一样对待它(Laravel是ORM框架的好例子)。

但你可以通过查询加入来模拟它。

这项工作只是为您提供其他模型数据而不是那些模型对象...

答案 2 :(得分:0)

请参阅Active Record: CodeIgniter

中的$this->db->join();标题

我知道codeigniter在这里不是那么好。所以我总是喜欢Yii而不是它。

答案 3 :(得分:-2)

尝试使用此连接表的查询

Select a.*,b.*
from table_one a
inner join table_two b where b.id=a.id
相关问题