簡體   English   中英

如何在Codeigniter中實現嵌套注釋2個層次

[英]how to implement nested comments 2 levels deep in codeigniter

我正在嘗試在我的網站上實施一個僅兩個級別的評論系統,例如,您將擁有主要評論並回復該評論,但此評論不再贅述:

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

這可行,但是它使用了多個查詢模型:

 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將它們索引到數組中,然后再次遍歷它們以查找其子級,這樣會更有效。 我還是不知道該怎么實現?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM