Gustavo Bordin
Gustavo Bordin

Reputation: 109

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.

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?

In models/index.js i have:

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

Upvotes: 0

Views: 391

Answers (1)

Anatoly
Anatoly

Reputation: 22758

Many-to-many relations are described using belongsToMany in Sequelize:

// 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:

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)

Upvotes: 2

Related Questions