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', }) }