如何在codeigniter中实现2级深层次的嵌套注释

时间:2013-02-04 22:43:01

标签: php codeigniter codeigniter-2

我正在尝试在我的网站上实施一个只有两个级别的评论系统,例如,您将获得主要评论并回复该评论,但它不会更进一步:

main comment 1
  (sub_comment1)
  (sub_comment2)

main comment 2
  (sub_comment1)
  (sub_comment2)
  (sub_comment2)

等...

有意义吗?

我在codeigniter中创建网站,但我认为基本的php解决方案可以。

我的数据库表中的每一行都有一个id和一个parent_id,如果父id为0,那么它是一个主注释,如果它是一个子注释,它将在parent_id中具有其父注释的id。

如何以正确的顺序输入带有父级和子级注释的二维数组。

我当前的代码是这样的:控制器:

 function status_comments($id){

    $this->load->model('status_model');//load the status model
    $this->load->model('comment_model');//load the comment model

    $status = $this->status_model->get_entry_and_category($id); 
    $comments = $this->comment_model->get_comments($id);   

    if($status !== false) {

        if($comments !== false) {

            foreach($comments as $comment){

                  if($comment->reply_id == 0){

                    $comment =   

                  }
            }


            $content_data['comments'] = $comments; 

        }        

        $content_data['status'] = $status; 
        $data['content'] = $this->load->view('status_view', $content_data, TRUE);
        $data['title'] = $status->title.' - High Value Status'; 
        $data['page_title'] = $status->title;//The page H1 tag
        $this->load->view('home', $data);   

    }
    else 
    { 
        $this->session->set_flashdata('invalid', '<p class="rejectionalert"><span>The status you tried to view does not exist.</span></p>');
        redirect('home'); 
    }

}

模型功能:

//Gets comments associated with an individual status   
function get_comments($status_id, $offset=null, $limit=null)
{
    $this->db->select('id, comment, nickname, created, reply_id');
    $this->db->from('comments');
    $this->db->where('active', 1);
    $this->db->where('status_id', $status_id);

    $query = $this->db->get(); 

    if ($query->num_rows() > 0) {

        return $query->result();      
    }

    return false;   
}

1 个答案:

答案 0 :(得分:0)

这可以使用但它使用多个查询,模型:

 function get_comments($status_id, $limit=NULL, $offset=NULL)
 {
    $this->db->where(array('status_id' => $status_id, 'reply_id' => 0));
    $query = $this->db->get('comments', $limit, $offset);

    $parents = $query->result_array();
    $comments = array(); 

    foreach($parents as $key => $comment)
    {
        array_push($comments, $comment);

        $this->db->order_by('created', 'ASC');
        $this->db->where(array('status_id' => $status_id, 'reply_id' => $comment['id']));

        $comments = array_merge($comments, $this->db->get('comments')->result_array());
    }

    return $comments;   

}

我认为对所有评论进行一次查询,通过他们的id将它们索引到一个数组中,并再次迭代它们以找到他们的孩子会更有效。我还不知道如何实现它?