如何在NodeJS Sequelize中按查询计数组

时间:2015-04-25 18:33:25

标签: node.js postgresql sequelize.js

在Rails中,我可以对模型的Likes数量执行简单的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,我不知道为什么,也不知道如何摆脱它。

2 个答案:

答案 0 :(得分:17)

This sequelize github issue看起来完全像你的情况:

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

答案 1 :(得分:5)

要解决此问题,我们需要升级到最新版本的sequelize并包含raw = true, 以下是经过大量迭代和偏离谷歌搜索后我的表现。

 getUserProjectCount: function (req, res) {
        Project.findAll(
            {
                attributes: ['User.username', [sequelize.fn('COUNT', sequelize.col('Project.id')), 'ProjectCount']],
                include: [
                    {
                        model: User,
                        attributes: [],
                        include: []
                    }
                ],
                group: ['User.username'],
                raw:true
            }
        ).then(function (projects) {
            res.send(projects);
        });
    }

我的参考模型是

//user
var User = sequelize.define("User", {
    username: Sequelize.STRING,
    password: Sequelize.STRING
});

//project
var Project = sequelize.define("Project", {
    name: Sequelize.STRING,
    UserId:{
         type:Sequelize.INTEGER,
         references: {
                 model: User,
                  key: "id"
         }
    }
});

Project.belongsTo(User);
User.hasMany(Project);
迁移后的

ORM创建'用户'& 'Projects'表进入我的postgres服务器。 这是ORM的SQL查询

SELECT 
  "User"."username", COUNT("Project"."id") AS "ProjectCount" 
 FROM 
    "Projects" AS "Project" 
    LEFT OUTER JOIN "Users" AS "User" ON "Project"."UserId" = "User"."id" 
 GROUP BY 
   "User"."username";