我有两个表
用户和评论
评论与用户有多对一的关系
试图想出一种使用ORM的方法来获得基于评论量的顶级用户
有什么建议吗?
您的查询应该如下所示:
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
翻译成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();