Home > Software design >  Sequelize: Model is not associated to Model2
Sequelize: Model is not associated to Model2

Time:12-30

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:

  • Title
  • Description
  • CreatedAt
  • UpdatedAt

Specification:

  • Title
  • Description
  • ProjectId (Foreign Key from Projects table)

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!

CodePudding user response:

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

  • Related