I’m building a web application with CodeIgniter.
Users can “love” or “hate” posts. These actions are stored in a table called post_rating with the following columns:
- id
- post_id
- user_id
- rating
Rating can either be 0 for neutral, 1 for love or 2 for hate.
In my model, I have returned some basic information for each post with the following function:
function get_posts($thread_id)
{
$this->db->select('id, user_id, date_posted, content');
$this->db->from('post');
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return $query->result();
}
}
I understand I need to join the post_rating table, but how would I go about also returning the love and hate counts in the same array as the title, content etc?
Thanks!
🙂
UPDATE!
Here is my MODEL at the moment:
function get_posts($thread_id)
{
$this->db->select('post.id, post.user_id, post.date_posted, post.content, post.status_visible, user.username, user.location, user.psn, user.clan, user.critic, user.pro, SUM(case when rating = 1 then 1 end) as love, SUM(case when rating = 2 then 1 end) as hate');
$this->db->from('post');
$this->db->join('user', 'user.id = post.user_id', 'left');
$this->db->join('post_rating', 'post_rating.post_id = post.id', 'left');
$this->db->where('thread_id', $thread_id);
$this->db->order_by('date_posted', 'asc');
$query = $this->db->get();
if ($query->num_rows() > 0)
{
$this->db->select('id');
$this->db->from('post_vote');
return $query->result();
}
}
You can use a
caseto sum up two different stats: