I have a warmup
and a warmup_step
. I am trying to create a warmup
with an association however when I try and create, it does not map the warmup_id
to the warmup_step
. What am I doing wrong?
// Warmup
module.exports = (sequelize, DATATYPES) => {
const Warmup = sequelize.define(
"warmup",
{
duration: { type: DATATYPES.INTEGER, allowNull: false },
name: { type: DATATYPES.STRING, allowNull: false },
},
{ underscored: true }
);
// Assign an associate function on the model
Warmup.associate = function (models) {
models.Warmup.hasMany(models.WarmupStep);
};
return Warmup;
};
// Warmup Step
module.exports = (sequelize, DATATYPES) => {
const WarmupStep = sequelize.define(
"warmup_step",
{
duration: { type: DATATYPES.INTEGER, allowNull: false }, // seconds
exercise_id: { type: DATATYPES.INTEGER, allowNull: false },
warmup_id: { type: DATATYPES.INTEGER, allowNull: false }, // Map to parent Warmup.
step_index: { type: DATATYPES.INTEGER, allowNull: false }, // position in warmup.
},
{ underscored: true }
);
// Assign an associate function on the model
WarmupStep.associate = function (models) {
models.WarmupStep.belongsTo(models.Warmup, { foreignKey: "warmup_id" });
};
return WarmupStep;
};
Create function:
Warmup.create(
{
name,
duration,
warmup_steps,
},
{
include: [WarmupStep],
}
)
.then((data) => res.send(data))
.catch((err) => {
console.log("here");
console.log(err);
});
I would expect the warmup
to be created and then use the id for the warmup_steps
but it is giving me the error message: 'warmup_step.warmup_id cannot be null'
. I assumed this is what creating with an association did for you? Or do I have to do this in two calls?
You should indicate warmup_id in the hasMany association as well:
models.Warmup.hasMany(models.WarmupStep, { foreignKey: "warmup_id" });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.