2013-02-04 29 views
0

我想實現我的網站評論系統是深只有兩個級別,例如,你將有主的評論和回覆評論,但它不會去任何進一步:如何實現嵌套評論2層深的笨

main comment 1 
    (sub_comment1) 
    (sub_comment2) 

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

等等

有意義嗎?

我創建CI中的網站,但我認爲一個基本的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; 
} 

回答

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,一個nd再次遍歷它們以找到他們的孩子。我仍然不知道如何實現?