How to count a group by query in NodeJS Sequelize

后端 未结 2 1130
囚心锁ツ
囚心锁ツ 2021-02-12 14:57

In Rails I can perform a simple ORM query for the number of Likes a model has:

    @records = Model
        .select( \'model.*\' )
        .select( \'count(likes         


        
相关标签:
2条回答
  • 2021-02-12 15:11

    This sequelize github issue looks totally like your case:

    User.findAll({
      attributes: ['User.*', 'Post.*', [sequelize.fn('COUNT', 'Post.id'), 'PostCount']],
      include: [Post]
    });
    
    0 讨论(0)
  • 2021-02-12 15:16

    To resolve this problem we Need to upgrade to latest version of sequelize and include raw = true, Here is How I had done after lot of iteration and off-course googling.

     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);
            });
        }
    

    where my reference models are

    //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);
    

    after migration ORM create 'Users' & 'Projects' table into my postgres server. Here is SQL Query by ORM

    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";
    
    0 讨论(0)
提交回复
热议问题