使用sequelize.js创建与多个外键的关联

问题描述:

我正在寻找使用sequelize.js来打一个电话和ping两个表。使用sequelize.js创建与多个外键的关联

我希望我的结果中找到我的第二个表中有两个外键匹配相应的数据 - “TIMEPERIOD”和“NODEID”

目前,无论不同的别名(S)的 - 只有我的查询结果匹配我指定的最后一个外键。因此在这种情况下的时间段。

associate: function (models) { 
    models.belowOcfBudget.belongsTo(models.belowOcf, { 
     foreignKey: 'nodeid', 
     targetKey: 'nodeid', 
     as: 'belowOcf_id' 
    }); 
    models.belowOcfBudget.belongsTo(models.belowOcf, { 
     foreignKey: 'timeperiod', 
     targetKey: 'timeperiod', 
     as: 'belowOcf_time' 
    }); 
} 

下面是我在我的路由器中包含此关联的地方。

BelowOCFBudget.findAll({ 
    raw: true, 
    include:[{ 
     model: models.belowOcf, 
     as: 'belowOcf_id' 
    }], 
    include:[{ 
     model: models.belowOcf, 
     as: 'belowOcf_time' 
    }] 

我怎么能有我的查询执行,并从具有匹配TIMEPERIOD和id两个表返回我的数据集?

你不应该包含你的关联模型两次。这导致在同一个表上的左加入,每个外键一个。 而是只包含一次,并将第二个外键的匹配作为附加where子句添加到include中。

没有测试它,但应该是这个样子:

BelowOCFBudget.findAll({ 
    raw: true, 
    include:[{ 
     model: models.belowOcf, 
     where: {belowOcf.timeperiod: timeperiod} 
    }], 
})