Open
Description
Issue Description
I was going through the association docs to create foreign key constraints for my tables in sqlite but i noticed when using Model.HasMany(Child)
by default the foreign key definition is allowNull: true
which defeats the purpose of using a foreign key constraint.
https://sequelize.org/docs/v6/core-concepts/assocs/
Im not sure if i missed anything but i couldnt find this anywhere in the docs and the associations docs doesnt explain this behavior properly.
Let me know if i'm missing anything
Additional context
This code would define the foreign key employeeId
with allowNull:true
sequelize.define("Employees", {
id: {
type: DataTypes.UUIDV4,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
allowNull: false
},
employeeType: {
type: DataTypes.INTEGER,
allowNull: false
}
}, {
indexes: [
{
using: "BTREE",
fields: ["employeeType"]
}
]
})
sequelize.define("Missions", {
id: {
type: DataTypes.UUIDV4,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
hours: {
type: DataTypes.INTEGER,
allowNull: false
},
missionName: {
type: DataTypes.STRING,
allowNull: true
},
missionDate: {
type: DataTypes.DATE,
allowNull: false
},
missionType: {
type: DataTypes.INTEGER,
allowNull: true
}
}
);
// 1 to many relationship between employees & missions
sequelize.models.Employees.hasMany(sequelize.models.Missions);
I had to refactor the code to this for the foreign key constraint to be effective
sequelize.define("Employees", {
id: {
type: DataTypes.UUIDV4,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
allowNull: false
},
employeeType: {
type: DataTypes.INTEGER,
allowNull: false
}
}, {
indexes: [
{
using: "BTREE",
fields: ["employeeType"]
}
]
})
sequelize.define("Missions", {
id: {
type: DataTypes.UUIDV4,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
employeeId: {
type: DataTypes.UUIDV4,
allowNull: false,
},
hours: {
type: DataTypes.INTEGER,
allowNull: false
},
missionName: {
type: DataTypes.STRING,
allowNull: true
},
missionDate: {
type: DataTypes.DATE,
allowNull: false
},
missionType: {
type: DataTypes.INTEGER,
allowNull: true
}
}
);
// 1 to many relationship between employees & missions
sequelize.models.Employees.hasMany(sequelize.models.Missions, {
foreignKey: 'employeeId',
as: 'missions'
});
Metadata
Metadata
Assignees
Labels
No labels
Activity