Search code examples
sequelize.jssequelize-clisequelize-typescript

Counting a column's data in Sequelize


I have two tables associated with each other in Sequelize and I want to count the following

Jobs table columns: 'id', 'name'

worker table colmuns: 'id', 'name', 'job_id'

Lets say we have 5 jobs available right now and lots of workers associated with the job_id I want to show job's 'id', 'name' and count how many workers has the same job_id

Example: {id: 1, name: Engineer, count: 6}; this means in worker's table 6 workers has job_id = 1

My query is like this:

Jobs.findAll({
attribute:['id', 'name'],
include: [
    {
    model: Worker,
    attributes: [[Sequelize.fn('count', Sequelize.col('job_id')), 'count']]
    }
],
group: ['Job.id', 'Worker.id']
})

Gives me the following result without count:

[
   {
    "id": 7,
    "name": "Doctor",
    "users": []
   },
   {
    "id": 1,
    "name": "Engineer",
    "users": [
              {
               "count": 1
              },
              {
              "count": 1
              },
              {
              "count": 1
              },
              {
              "count": 1
              },
              {
              "count": 1
              },
              {
              "count": 1
              }
            ]
         },
     {
       "id": 4,
       "name": "Pilot",
       "users": []
     }
]

Whereas it should count all job_id of the users as shows as:

    "id": 1,
    "name": "Engineer",
    "count": 6

Solution

  • you have to define count in Job attributes like this .

    Jobs.findAll({
        attribute: ['id', 'name', [sequelize.fn("COUNT", sequelize.col('Worker.job_id')), "count"]],
        include: [
            {
                model: Worker,
                attributes: []
            }
        ],
        group: ['Worker.job_id', 'Job.id']
    })
    

    hope this'll help you .