使用 MySQL 方言的 Sequelize 在迁移模型时无法生成外键

Sequelize using MySQL dialect failed to generate foreign key while migrating models

      Employee.associate = function (models) {
            // associations can be defined here
            Employee.belongsTo(models.Company, {
                foreignKey: "companyId",
                onDelete: "CASCADE"
            })
        };

但是在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"
        }
      },
    
  • 它对我来说很成功。