Sequelize: Model is not associated to Model2

I'm trying to make a query with a few models in Sequelize. I have 2 models, one is Project and the other one is Specification. A project can have many Specifications, and a specification can only belong to one project. The table structure is:

Project:

Specification:


This is the relation I have for Specifications -> Projects:

Project.belongsToMany(Specification);

The function i'm using to retrieve the data is this. Basically it gets all the data, including all the possible associations:

// Retrieve all Projects from the database.
exports.findAll = (req, res) => {
  Project.findAll({
  include: [{
    all: true
  }]
})
.then(data => {
  res.send(data);
})
.catch(err => {
  res.status(500).send({
    message:
      err.message || "Some error occurred while retrieving projects."
  });
});
};

Finally, the error I'm getting is this:

{"message":"specification is not associated to project!"}

Can someone help me or teach me about how to accomplish the query? I've been trying and cannot get the right result. Thank you!

Upvotes: 0

Views: 670

Answers (2)

Jaspal Singh
Jaspal Singh

Reputation: 209

Use hasMany instead of belongsToMany to define relation

Project.hasMany(Specification, {
  foreignKey: { name: 'ProjectId' },
  targetKey: 'ProjectId',
  constraints: false,
  as: 'specifications',
}),

Upvotes: 0

Anatoly
Anatoly

Reputation: 22768

If you describe your structure as

A project can have many Specifications, and a specification can only belong to one project

then it's a usual 1:N relationship and in this case, hasMany association should be used instead of belongsToMany because belongsToMany is used to indicate M:N relationship and in that case, you will need a junction table/model. That said you only need to replace

Project.belongsToMany(Specification);

with

Project.hasMany(Specification, { foreignKey: 'ProjectId' });

I always prefer to indicate a foreign key explicitly

Upvotes: 1

Related Questions