Sequelize with join, group by, having, order by

雨燕双飞 提交于 2019-12-31 02:53:16

问题


How this query can be written using ORM?

SELECT p.id, 
    p.name, 
    COUNT(c.id) counter 
FROM Posts p 
LEFT JOIN Comments c 
    ON c.post_id = p.id 
WHERE p.rating > 100 
GROUP BY p.id
HAVING counter > 10
ORDER BY counter DESC 
LIMIT 5

回答1:


Try this:

Post.findAll({
  where: {rating: {gt: 100}},
  include: [Comments],
  having: ['COUNT(?) >= ?', '`comment`.`id`', 10]
})

Read my research by this question.

i use sequelize@2.0.0-dev9




回答2:


Since there is aggregated column counter in your query I think there is no standard ORM method to fetch entities by this query. But Sequelize provide the way to run raw SQL expression and parse results in any model you need. Or even deeper you can parse response yourself creating as complex result as you need.

Here is related docs for this case: http://docs.sequelizejs.com/manual/tutorial/raw-queries.html



来源:https://stackoverflow.com/questions/21057302/sequelize-with-join-group-by-having-order-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!