- 我正在使用sequelize命令来创建模型并将其迁移到 在MySql数据库中生成表。
- 要生成新模型:
sequelize model:create --name Demo --attributes column:string
- 在模型和迁移文件生成后,添加几行代码以使用给定的代码片段进行关联和外键约束 :
- 在公司的派生/子表中:
Employee.associate = function (models) {
// associations can be defined here
Employee.belongsTo(models.Company, {
foreignKey: "companyId",
onDelete: "CASCADE"
})
};
在基/父表公司中:
Company.associate = function (models) { // associations can be defined here Company.hasMany(models.Employee,{ foreignKey:"companyId", }) };
但它没有反射(reflect)在Table->ALTER TABLE->ForeignKey Constraints中。
最佳答案
你的外键搞砸了......我认为它应该看起来更像下面这样,因为你希望在员工表中有一个名为companyId的字段,该字段引用公司表的id字段
Employee.associate = function (models) {
// associations can be defined here
Employee.belongsTo(models.Company, {
sourceKey: "companyId",
foreignKey: "id",
onDelete: "CASCADE"
})
};
和
Company.associate = function (models) {
// associations can be defined here
Company.hasMany(models.Employee,{
foreignKey:"companyId",
})
};
这个只会假设你的源键是你的主键,可能是 id
关于mysql - 迁移模型时使用 MySQL 方言的 Sequelize 无法生成外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59628741/