0

我有 2 个不同的表:声誉和帖子。POSTS 有与其相关的详细信息,如 post_id、user_id、post_content... 等等。REPUTATION 包含 post_id 和 user_id 等详细信息。如果表中存在一对,则 post_id 已被 user_id +1。

在我的主页上,我使用分页来显示 5 个帖子/页,并且只从 POSTS 表中获取。此外,我试图从 REPUTATION 表中获取 $_SESSION 中的“user_id”的“post_id”。

public function index()
{
    $this->load->model('themodel');
    $this->load->library('pagination');
    $config['base_url'] = site_url('trial/index');
    $config['total_rows'] = $this->themodel->total_rows('posts');
    $config['per_page'] = 5;
    //$config['display_pages'] = FALSE;
    $this->pagination->initialize($config);

    $offset = $this->uri->segment(3);

    $data['details'] = $this->themodel->list_posts($config['per_page'], $offset);

    $data['links'] = $this->pagination->create_links();


    //Check for session and load the reputation data
    if($this->session->userdata('loggedIn') && $this->session->userdata('user'))
    {
        //fetch reputation by user
        $data['repbyuser'] = $this->themodel->getrepbyuser();
    }

    $this->load->view('home_view', $data);

}

在模型部分:

public function list_posts($limit, $start)
{
    $this->db->select('post_id, user_id, post_title, post_content, total_reputation, post_time, total_reviews');
    return $this->db->get('posts', $limit, $start)->result_array();
}

public function getrepbyuser()
    {
        $this->db->select('post_id');
        $this->db->where('user_id', $this->session->userdata('user'));
        $result = $this->db->get('reputation');
        if($result->num_rows() > 0)
            return $result->result_array();
    }

现在在我的主页上,我正在遍历$details数组,但我不确定如何匹配两个表的结果。

如果我做错了什么,请指导。任何建议将不胜感激。

4

1 回答 1

1
function getrepbyuser()
{
    $data   = array();
    $this->db->select('post_id');
    $this->db->where('user_id', $this->session->userdata('user'));
    $result = $this->db->get('reputation');
    if($result->num_rows() > 0){
        //return $result->result_array();
        $temp   = $result->result_array();
        foreach( $temp as $each ){ #for returning a single dimentional array
            $data[] = $each['post_id'];
        }
    }
    return $data;       
}

现在在视图页面中,您将执行以下操作:

foreach( $details as $each ){   #loop for the posts
    $liked  = false;
    if( in_array($key['post_id'], $repbyuser) ){    #check if the post is liked or not
        $liked  = true;
    }

    if( $liked ){
        #button for dislike
    }else{
        #button for like
    }
}
于 2013-09-17T12:40:08.563 回答