这是我需要从数据库中得到的结果
{comment: 'hello there', user: [{name: 'sahan', id: 1}], id: 2}
征求意见的函数
public function get_comments(){
$query = $this->db->get('comments');
return $query->result_array();
}
我有一个评论表和一个用户表,当一个用户对某件事情发表评论时,该表的
comment is saved as follows
comment > Comment text
user: userid
因此,当数据显示时,我需要codeigniter用从用户表中找到的用户数据填充用户字段
有人知道如何做到这一点,我在SailsJS中使用这个功能,但不知道如何在CodeIG这里做到这一点。Sails.js填充嵌套的关联。
Codeigniter的活动记录没有SailJS的活动记录高级,但你可以在同一个方法中用两个查询来实现你的要求。
我假设 comments
表有一个外键到 users
列表 user_id
领域:
public function get_comments() {
/* Get all the comments */
$query = $this->db->get('comments');
$comments = $query->result_array();
/* Loop through each comment, pulling the associated user from the db */
foreach $comments as &$comment {
$query = $this->db->get_where('users', array('id' => $comment['user_id']));
$user = $query->result_array();
/* Put the user's data in a key called 'user' within the comment array */
$comment['user'] = $user;
/* Remove the unnecessary user_id and $user variable */
unset($comment['user_id']);
unset($user);
}
return $comments;
}