它可以做到,但绝对没有限制在数据库中。在您的情况下,ModuleLabel
中的module_id
字段可能会引用user
或permit
表。我可以向你展示一些实现草图,但是我会建议重构模式,例如创建UserLabel
和PermitLabel
型号,其外部约束条件为User
和Permit
。但是,下面是你如何做你的方式
// in User model definition
classMethods: {
associate: function(models){
this.hasMany(models.ModuleLabel, { foreignKey: 'module_id', constraints: false });
}
}
// in Permit model definition
classMethods: {
associate: function(models){
this.hasMany(models.ModuleLabel, { foreignKey: 'module_id', constraints: false });
}
}
以上的关联使我们能够查询两个User
或Permit
时加入ModuleLabel
模型。最重要的部分是记住防止创建数据库约束的constraints: false
。让我们继续。 Label
模型不需要任何关联,只有字段声明。最后一个模型是ModuleLabel
// in ModuleLabel model definition
classMethods: {
associate: function(models){
this.belongsTo(models.Label, { foreignKey: 'label_id' });
this.belongsTo(models.User, { foreignKey: 'module_id', constraints: false });
this.belongsTo(models.Permit, { foreignKey: 'module_id', constraints: false });
}
}
现在,为了执行所需的查询,你可以做到这一点
models.Permit.findAll({
include: [
{
model: models.ModuleLabel,
include: [
{
model: models.Label,
where: { module_name: 'permit' }
}
]
}
]
}).then((result) => {
console.log(result);
});
上面的查询会生成SQL类似这样的介绍如下
SELECT * FROM Permits
LEFT OUTER JOIN ModuleLabels
ON Permits.id = ModuleLabels.module_id
INNER JOIN Labels
ON ModuleLabels.label_id = Labels.id
AND Label.module_name = 'permit';
是这些表之间有任何外键关系吗? –
@AtulAgrawal:更新问题 – Kepler
这里有什么进展? – piotrbienias