有没有一种方法可以阻止sequelize sync()添加特定的外键?

时间:2020-06-10 18:28:30

标签: javascript mysql synchronization sequelize.js

这是问题的要点。

我有一个表格“ Boxes”。可以与一个框关联的项目有多个表(“小部件”,“ Dohickies”,“ Thingamabobs”)。

我有一个关系表“ ItemsInBox”,其中包含BoxId,ItemId,itemType。

在我的模型中,我使用“ ItemsInBox”作为“直通”表来创建关联(belongsToMany,hasMany),但是没有与各种item表关联的实际外键,因为这会引起外键冲突。所有这些都很好。

问题在于,当我为模型编写测试时,我使用sequelize.sync()生成表。 Sync()自动为所有关联添加外键。

我无法在模型定义中使用“ references”属性来创建关联,因为“ Boxes”表需要能够引用3个不同的表,但是就我而言,references属性不能是数组可以告诉。

是否可以告诉sequelize.sync()跳过为特定关联添加外键的方法?

注意:当前正在使用sequelize v3,但正在努力升级到v5。

1 个答案:

答案 0 :(得分:0)

弄清楚该怎么做。

在初始化脚本中,您必须遍历所有模型并执行[model] .associate(models)。

类似

const tableNames = Object.keys(models)
    for (let modelName of tableNames) {
        let model = models[modelName]
        if (typeof model.associate === 'function') model.associate(db)
    }

在模型中,您具有关联功能。

在v3 / v4中

classMethods: {
    associate: function (models) {
      ...
    }
}  

在v5中

[model].associate(){
}

或者如果您使用类定义而不是定义,那么您将拥有一个关联属性。

创建第二个函数来创建非外键关联。

在v3 / v4中

classMethods: {
    associate: function (models) {
      ...
    },
    nfkAssociate: function (models) {
      [model].belongsTo(...)
    }
}  

在v5中

[model].nfkAssociate = function (models) {
    [model].belongsTo(...)
}

然后在您的初始化脚本中

const tableNames = Object.keys(models)
for (let modelName of tableNames) {
    let model = models[modelName]
    if (typeof model.associate === 'function'){ 
       model.associate(db)
    }
}
db.doNFKAssociations = function () {
    for (let modelName of tableNames) {
        const model = db[modelName]
        if (model.nfkAssociate) {
            model.nfkAssociate(db)
        }
    }
}
if (!config.delayNFKAssociations) {
    db.doNFKAssociations()
}

默认情况下,您同时运行associate()和nfkAssociate()。如果您遇到某种情况,例如运行自动化测试,则可以在初始化配置中添加一个额外的属性“ delayNFKAssociations”,这将阻止执行辅助关联。

您在哪里使用sync():

await sqldb.sequelize.sync({force: true }).then(() => {
  // create all of the associations that shouldn't have foreign keys associated
  sqldb.doNFKAssociations()
})

现在,您可以在运行sync()方法之后创建关联,并且不会收到不需要的外键。