简体   繁体   English

Sequelize 从外键获取 N:M 关联

[英]Sequelize get N:M association from foreign key

I have a schema where I have an Asset which has many threats and each threat has many countermeasures.我有一个架构,其中我有一个资产,其中有很多威胁,每个威胁都有很多对策。 What I want to do is given the id of an asset to get the list of the threats, and the list countermeasures for each threat, of that asset.我想要做的是给定资产的 id 以获取该资产的威胁列表以及针对每个威胁的对策列表。 How can I achieve that?我怎样才能做到这一点?

I don't think my code will provide any help, but here you go anyway:我不认为我的代码会提供任何帮助,但无论如何你都可以:

Asset.belongsToMany(Threat, { through: 'asset-threat' });
Threat.belongsToMany(Asset, { through: 'asset-threat' });

Countermeasure.belongsToMany(Threat, { through: 'countermeasure-threat' });
Threat.belongsToMany(Countermeasure, { through: 'countermeasure-threat' });

All the association stuff are here.所有协会的东西都在这里。 I let sequelize handle everything that has to do with keys foreiggn and not.我让 sequelize 处理与密钥有关的所有事情。

Edit编辑

Something I tried to do that doesnt work but explains really well what I want to achieve is the following:我试图做的事情不起作用,但很好地解释了我想要实现的目标如下:

const asset = await Asset.findOne({ where: { id } });

return await asset.getThreats({
    include: Countermeasure
});

At least you should indicate include option values as an array:至少您应该将include选项值指示为数组:

return await asset.getThreats({
    include: [Countermeasure]
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM