Question

I have 2 tables

The users and comments

The comments have a many to one relationship with the users

Trying to think of a way using ORM to get top users based on amount of comments

Any suggestions?

Was it helpful?

Solution

Your query should look like this:

SELECT users.username, COUNT(comments.id) AS total 
FROM users 
INNER JOIN comments 
ON users.id = comments.user_id 
GROUP BY users.username 
ORDER BY COUNT(comments.id) DESC

Translated to ORM:

ORM::factory('user')
   ->select('user.username', array('COUNT("comments.id")', 'total'))
   ->join('comments', 'INNER')
   ->on('user.id', '=', 'comments.user_id')
   ->group_by('user.username')
   ->order_by('total', 'DESC')
   ->find_all();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top