使用 MySQL 方言的 Sequelize 在迁移模型时无法生成外键
Sequelize using MySQL dialect failed to generate foreign key while migrating models
- 我正在使用 sequelize 命令来创建模型并将其迁移到
在 MySql 数据库中生成 Tables。
- 生成新模型:
sequelize model:create --name Demo --attributes column:string
- 并且在 Model 和 migration 文件生成后,添加几行代码来建立 关联和外键constraints 使用给定的代码片段:
- 在 Derived/Child Table 公司:
Employee.associate = function (models) {
// associations can be defined here
Employee.belongsTo(models.Company, {
foreignKey: "companyId",
onDelete: "CASCADE"
})
};
在Base/Parenttable公司:
Company.associate = function (models) {
// associations can be defined here
Company.hasMany(models.Employee,{
foreignKey:"companyId",
})
};
但是在Table->ALTER TABLE->ForeignKey Constraints.
中没有体现
你的外键搞砸了....我认为它应该看起来更像下面的东西,因为你希望在你的员工中有一个名为 companyId 的字段 table 引用公司的 id 字段 table
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 DB及其
table,仅当我们将迁移文件与模型文件一起更改时。
- 我们必须在迁移文件中添加如下内容:
companyId:{
type: Sequelize.INTEGER,
onDelete: "CASCADE",
references: {
model: "Comapany",
key: "id"
}
},
- 它对我来说很成功。
- 我正在使用 sequelize 命令来创建模型并将其迁移到 在 MySql 数据库中生成 Tables。
- 生成新模型:
sequelize model:create --name Demo --attributes column:string
- 并且在 Model 和 migration 文件生成后,添加几行代码来建立 关联和外键constraints 使用给定的代码片段:
- 在 Derived/Child Table 公司:
Employee.associate = function (models) {
// associations can be defined here
Employee.belongsTo(models.Company, {
foreignKey: "companyId",
onDelete: "CASCADE"
})
};
在Base/Parenttable公司:
Company.associate = function (models) { // associations can be defined here Company.hasMany(models.Employee,{ foreignKey:"companyId", }) };
但是在Table->ALTER TABLE->ForeignKey Constraints.
中没有体现你的外键搞砸了....我认为它应该看起来更像下面的东西,因为你希望在你的员工中有一个名为 companyId 的字段 table 引用公司的 id 字段 table
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 DB及其 table,仅当我们将迁移文件与模型文件一起更改时。
- 我们必须在迁移文件中添加如下内容:
companyId:{ type: Sequelize.INTEGER, onDelete: "CASCADE", references: { model: "Comapany", key: "id" } },
- 它对我来说很成功。