0
votes

I have 2 models Assignment and Area in defined each one in seperate file like this :

./models
--Area.js
--Assignment.js
--index.js

Area.js :


    const Area = sequelize.define('area',{
        id: {
            type: Sequelize.INTEGER,
            autoIncrement: true,
            primaryKey: true
        },
        name: {
            type: Sequelize.STRING,
        }
        }, {
            timestamps: false
        });
     Area.hasMany(Assignment, { foreignKey:'areaId'});

Assignment.js :


    const Assignment = sequelize.define('assignment',{
        id: {
          type: Sequelize.INTEGER,
          autoIncrement: true,
          primaryKey: true,
        }
      }, {
        timestamps: false
      });
    Assignment.associate = models => {
        models.Assignment.belongsTo(models.Area, {
            foreignKey: 'areaId',
            onDelete: "CASCADE",
        });
    };

When i try to find some assignments with areas information (join) with Include property i got an error saying that : area is not associated to assignment!


    Assignment.findAll({
            include: [{ model: Area }]
        }).then((assignments) => {
            res.status(200).json(assignments)
        }).catch((e) => {
            res.status(500).json({ error: e.message })
        })

Thanks in advance.

2

2 Answers

0
votes
Area.hasMany(Assignment, { foreignKey:'areaId'});

So the column areaId should be in your Assignment.js. But can't see it in your Assignment model.

models.Assignment.belongsTo(models.Area, {
            foreignKey: 'areaId',
            onDelete: "CASCADE",
        });

Also this is correct only if you have a column called areaId in your Assignment.js

In conclusion you miss the areaId column in the Assignment model.

0
votes

It seems to me that you are missing the enclosing associate method:

Area.associate = models => {
    models.Area.hasMany(Assignment, { foreignKey:'areaId'})
};

and the column areaId should be in your Assignment.js too