Farhan C K
Farhan C K

Reputation: 1158

Sequelize count fn add where clause

The below code works fine, but i only want to count students who are present. how can i do that.

Classroom.findAll({
  attributes:{  
        include : [
          [sequelize.fn('COUNT', sequelize.col('student.id')), 'count'] // here.  where student.present = true;
        ],
      },
      include:  [{ attributes: [], model: Student, as : 'student', }], 
      group: [sequelize.col('Classroom.id')]
})

Upvotes: 2

Views: 5282

Answers (1)

Vivek Doshi
Vivek Doshi

Reputation: 58593

You can add that condition in include model :

Classroom.findAll({
  attributes:{  
        include : [
          [sequelize.fn('COUNT', sequelize.col('student.id')), 'count']
        ],
      },
      include:  [
          { 
              attributes: [], 
              model: Student, 
              as : 'student', 
              where : { present : true } // <--------- HERE
            }
        ], 
      group: [sequelize.col('Classroom.id')]
})

Upvotes: 2

Related Questions