node.js – 如何通过NodeJS Sequelize中的查询计数一个组

在Rails中,我可以对一个模型的喜欢数量执行一个简单的ORM查询:

    @records = Model
        .select( 'model.*' )
        .select( 'count(likes.*) as likes_count' )
        .joins( 'LEFT JOIN likes ON model.id = likes.model_id' )
        .group( 'model.id' )

这会生成查询:

SELECT  models.*, count(likes.*) as likes_count
FROM "models" JOIN likes ON models.id = likes.model_id
GROUP BY models.id

在Node Sequelize中,任何类似操作的尝试都会失败:

return Model.findAll({
    group: [ '"Model".id' ],
    attributes: ['id', [Sequelize.fn('count', Sequelize.col('"Likes".id')), 'likes_count']],
    include: [{ attributes: [], model: Like }],
});

这会生成查询:

SELECT
    Model.id,
    count(Likes.id) AS likes_count,
    Likes.id AS Likes.id           # Bad!
FROM Models AS Model
LEFT OUTER JOIN Likes
    AS Likes
    ON Model.id = Likes.model_id
GROUP BY Model.id;

哪个产生错误:

column "Likes.id" must appear in the GROUP BY clause or be used in an aggregate function

这是错误地选择likes.id,我不知道为什么,也不知道如何摆脱它.

最佳答案
This sequelize github issue看起来完全像你的情况:

User.findAll({
  attributes: ['User.*', 'Post.*', [sequelize.fn('COUNT', 'Post.id'), 'PostCount']],
  include: [Post]
}

转载注明原文:node.js – 如何通过NodeJS Sequelize中的查询计数一个组 - 代码日志