显示以前喜欢的按钮背后的逻辑不同

时间:2013-09-17 12:31:30

标签: php codeigniter social-media-like

我有两个不同的表:声誉和帖子。 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数组,但我不确定如何匹配表中的结果。

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

1 个答案:

答案 0 :(得分: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
    }
}