根据帖子数量获得用户排名(Codeigniter)

问题描述 投票:2回答:3

我有许多用户将内容发布到POSTS表。

id     user_id     content

1        1       text
2        3       text
3        1       text
4        1       text
5        2       text
6        3       text

现在,我想通过最高职位(行)获得单个用户排名。我对如何获得结果感到困惑!

codeigniter
3个回答
0
投票

假设您正在使用查询构建器,则可以使用以下语句获取所需的结果:

$this->db->select('user_id, count(content) as total_posts')
    ->group_by('user_id')
    ->order_by('total_posts', 'DESC')
    ->limit(1)
    ->get('POSTS')
    ->row();

0
投票

这个问题已经解决了。以下是我如何做到这一点的解释:

模型

public function get_user_ranking()
{   

    $this->db->select('user_id, count(id) as total_posts');
    $this->db->group_by('user_id');
    $this->db->order_by('total_posts', 'DESC');
    $query = $this->db->get('posts');
    return $query->result();
}

调节器

$data['user_ranking'] = $this->post_model->get_user_ranking();

视图

$rank = 1; foreach($user_ranking as $row)
{
    if( $row->user_id == $user->id)
    {
        echo $rank;
        break;
    } 
    $rank++;
}

0
投票
public function get_user_ranking()
{   

    $this->db->select('user_id, count(id) as total_postings');
    $this->db->from('posts');
    $this->db->group_by('user_id');
    $this->db->order_by('total_posts', 'DESC');
    return $this->db->get()->result();
}
© www.soinside.com 2019 - 2024. All rights reserved.