Codeigniter填充嵌套关联

时间:2015-05-23 02:30:14

标签: sql codeigniter mysqli sails.js

这是我需要的数据库结果

{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来填充用户字段,其中包含从users表中找到的用户数据

有谁知道怎么做? 我在SailsJS中使用了这个功能,但是不知道如何在CodeIG中做到这一点 Sails.js populate nested associations

1 个答案:

答案 0 :(得分:1)

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;
}