使用 Sequelize 按连接 table 计数列排序

Order by a join table count column using Sequalize

一段时间以来,我一直在努力让它发挥作用,希望能得到一些见解。

目标:我正在尝试按照帖子目前的点赞数量对帖子进行排序。

当前:

const posts = await db.post.findAll({
    include: [ db.user, { model: db.like_post, where: { user_id: user }, required: false } ],
    where: { category },
    group: [ [ sequelize.col('like_posts.post_id') ] ],
    order: [ [ sequelize.fn('count', sequelize.col('like_posts.post_id')), 'DESC' ] ]
});

我目前遇到的错误是:

"message": "column \"post.id\" must appear in the GROUP BY clause or be used in an aggregate function",

任何人有任何建议我可能做错了什么才能获得正确的帖子顺序?

再次感谢所有的帮助和提示。

因为您使用聚合函数 count SELECT 和 FROM 之间列出的所有其他字段应该在 GROUP BY 中列出。 如果您只想通过 like_post 中相关记录的计数对 post 进行排序,并保留 post 中的所有字段以及 user 中包含的所有字段,您应该在 order选项。

像这样:

order: [[sequelize.literal('(select count(*) from like_post where like_post.post_id=post.id)', 'DESC']