'table association not created One-To-Many sequelize node
I was creating associations for my database. But she did not create all the associations, for example, she did not link the contracts with the payroll. I tried the options from the database, but they did not help. Tell me what I can try to do and what I'm doing wrong?
Create association
db.Contracts.hasMany(db.Payrolls, {
foreignKey: {
name: 'contract_id',
sourceKey: 'id',
}
})
db.Payrolls.belongsTo(db.Contracts, {
foreignKey: {
name: 'contract_id',
targetKey: 'id',
}
})
Create Contracts
module.exports = (sequelize, DataTypes) => {
const Contracts = sequelize.define("Contracts", {
id: {
type: DataTypes.STRING,
allowNull: false,
primaryKey: true,
autoIncrement: false
},
month_pay: {
type: DataTypes.INTEGER,
allowNull: false
}
}, { timestamps: false });
return Contracts;
};
Create Payrolls
module.exports = (sequelize, DataTypes) => {
const Payrolls = sequelize.define("Payrolls", {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true
},
pay_date: {
type: DataTypes.DATE,
allowNull: false,
},
amount: {
type: DataTypes.INTEGER,
allowNull: false
}
}, { timestamps: false });
return Payrolls
};
e.g. working associations:
module.exports = (db) => {
//#region One-To-Many Contracts->Courses
db.Courses.hasMany(db.Contracts, {
foreignKey: {
name: 'course_name',
sourceKey: 'name',
primaryKey: true,
}
})
db.Contracts.belongsTo(db.Courses, {
foreignKey: {
name: 'course_name',
targetKey: 'name',
primaryKey: true,
}
})
//#endregion
//#region One-To-Many Contracts->Pupils
db.Pupils.hasMany(db.Contracts, {
foreignKey: {
name: 'pupil_id',
sourceKey: 'id',
primaryKey: true,
}
})
db.Contracts.belongsTo(db.Pupils, {
foreignKey: {
name: 'pupil_id',
targetKey: 'id',
primaryKey: true,
}
})
//#endregion
//#region One-To-Many Payrolls->Contracts
db.Contracts.hasMany(db.Payrolls, {
foreignKey: {
name: 'contract_id',
sourceKey: 'id',
}
})
db.Payrolls.belongsTo(db.Contracts, {
foreignKey: {
name: 'contract_id',
targetKey: 'id',
}
})
//#endregion
return db
}
if you need the project itself (its part of the database)
Solution 1:[1]
Looking at the Sequelize v7 documentation for hasMany and belongsTo
https://sequelize.org/api/v7/classes/model#hasMany
https://sequelize.org/api/v7/classes/model#belongsTo
It appears that those sourceKey and targetKey properties that you're passing into the foreignKey objects should be their own properties in the options objects, rather than nested inside of foreignKey.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | boc4life |
