0

I have two tables "project" and "company". I have created their models as 'Project' and 'Company' in sequelize.

Project table contains

project_id company_id project_name
1 1 project1
2 2 project2
3 2 project3

Company table contains

company_id company_name
1 xyz
2 test
3 abc

my requirement is to get all companies in the Company table and the no of projects they have.

i have wrote the query in sequelize as

const result = await Company.findAll({
    attributes: [ ['company_id', 'id'] ,'company_name', [Sequelize.fn('COUNT', 'Project.project_id'), 'no_of_projects'] ],
    include: [{ model: Project, attributes: [] }],
    group: ['company_id'],
    order: [
        [sortBy, sortOrder]
    ],
    offset: index,
    limit: limit,
    subQuery: false
})

but i am getting no_of_projects as 1 instead of 0 for company "abc" as it doesn't have any project. I need to get no_of_projects as 0 if there is no project for the company. i am new to sql and sequelize. can anyone please help me in solving this. thanks in advance.

these are the associations

Company.associate = function(models) { Company.hasMany(models.Project, { foreignKey: "company_id" }) }

Project.associate = function(models) { Project.belongsTo(models.Company, { foreignKey: 'company_id', }) }

Praveen Reddy
  • 33
  • 1
  • 9

2 Answers2

1

I have found the mistake in my sequelize query. Instead of

[Sequelize.fn('COUNT', 'Project.project_id')

It worked when I replace that with

[Sequelize.fn('COUNT', Sequelize.col('project_id'))

I need to specify that as a column to sequelize otherwise it is considering empty string as a value. That's why I got count as 1 instead of 0.

ParisaN
  • 1,816
  • 2
  • 23
  • 55
Praveen Reddy
  • 33
  • 1
  • 9
0

If you want SQL then you can use following:

select c.company_id, c.company_name, count(p.project_id) as num_of_project
  from company c left join project p on p.comapny_id = c.company_id
group by c.company_id, c.company_name
Popeye
  • 35,427
  • 4
  • 10
  • 31