I've seen this problem a lot in different forums but I haven't been able to fix it. I'm using Express and PostgreSQL with Sequelize.
Basically I have two models: Campus and academic manager. It's a one to one relation between the two, Campus has one academic manager.
I've implemented both models and the association works, I can see it beeing displayed in mi database in the postgres server. But when I try to implement my get request of campus, I try to include the manager information, without success. I keep receiving the same error:
SequelizeEagerLoadingError: academic_manager is not associated to campus!
I believe my problem has to do with include
Here are my code snippets:
campus.js
const campus = (sequelize, DataTypes) =>{
const Campus = sequelize.define('campus', {
name: {
type: DataTypes.STRING,
allowNull: false,
},
manager: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: 'academic_manager',
key: 'id'
}
}
});
Campus.associate = models => {
Campus.hasOne(models.Manager, { foreignKey: 'id'});
}
return Campus;
};
export default campus;
academic_manager.js
const manager = (sequelize, DataTypes) =>{
const Manager = sequelize.define('academic_manager', {
name: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false
}
});
Manager.associate = models => {
Manager.belongsTo(models.Campus, { foreignKey: 'id'});
}
return Manager;
};
export default manager;
And the get method:
router.get('/', async (req, res) => {
const campus = await req.context.models.Campus.findAll({
include: [
{ model: req.context.models.Manager }
]
});
return res.send(campus);
});
The get request works without the include. I know the association is achieved because when I describe my campus table and my manager table I have this:
TABLE "campus" CONSTRAINT "campus_manager_fkey" FOREIGN KEY (manager) REFERENCES academic_manager(id)