简体   繁体   English

Sequelize - 多对多关系

[英]Sequelize - many to many relationship

I have multiple tables relating to each other, what i want to do now is create a many to many relationship between Document and Tag .我有多个相互关联的表,我现在要做的是在Document and Tag之间创建多对多关系。

A single document can have many tags and a single Tag can have many Documents , How can i do this many to many relationship in sequelize?一个文档可以有很多标签,一个标签可以有很多文档,我怎样才能在sequelize中建立这种多对多的关系?

In models/index.js i have:models/index.js我有:

Tab.sync().then(() => {
    Group.sync().then(() => {
        User.sync().then(() => {
            Document.sync().then(() => {
                Reference.sync().then(() => {
                    Tag.sync().then(() => {
                        User.hasMany(Group, {foreignKey: 'userAssigned', as: 'groups'})
                        Group.belongsTo(User, {foreignKey: 'userAssigned', as: 'user'})
                        Document.belongsTo(Group, {foreignKey: 'groupId', as: 'group'})
                        Group.hasMany(Document, {foreignKey: 'groupId', as: 'documents'})
                        Tab.hasMany(Group, {foreignKey: 'tabId', as: 'groups'})
                        Group.belongsTo(Tab, {foreignKey: 'tabId', as: 'tab'})
                        Document.hasMany(Reference, {foreignKey: 'docId', as: 'references'})
                        Reference.belongsTo(Document, {foreignKey: 'docId', as: 'docs'})




                        //trying to create many to many relationship here//

                        Document.hasMany(Tag)
                        Tag.hasMany(Document)
                        //---------------------//
                    })
                })
            })
        })
    })
})

ps: i've already read about through parameter, but i cannot understand how it would work ps:我已经阅读了through参数,但我不明白它是如何工作的

Many-to-many relations are described using belongsToMany in Sequelize:在 Sequelize 中使用belongsToMany来描述多对多关系:

// Do you already have the DocumentTag model and a table?
// I'm assuming here DocumentTag has docId and tagId fields
Document.belongsToMany(Tag, { through: DocumentTag, foreignKey: 'docId', otherKey: 'tagId' })
Tag.belongsToMany(Document, { through: DocumentTag, foreignKey: 'tagId', otherKey: 'docId' })

To get documents along with linked tags you can query like this:要获取带有链接标签的文档,您可以像这样查询:

const docs = await database.Document.findAll({
   where: {
    // here are your search conditions
   },
   include: [database.Tag]
})

To add tags to a certain document you can call the addTags model instance method:要将标签添加到某个文档,您可以调用addTags model 实例方法:

const tags = await database.Tag.findAll({
   where: {
    // here are your search conditions
   },
   // to link tags to documents we don't need all attributes but `id`
   attributes: ['id']
})
const doc = await database.Document.findById(documentId)
await doc.addTags(tags)

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

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