Продолжить - отношения многие ко многим - PullRequest
0 голосов
/ 11 июля 2020

У меня есть несколько таблиц, связанных друг с другом, сейчас я хочу создать отношения «многие ко многим» между Document and Tag.

Один документ может иметь много тегов и один тег может иметь много документов , как я могу сделать это много ко многим отношения в продолжении?

в 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: я уже читал о параметре through, но не могу понять, как он будет работать

1 Ответ

1 голос
/ 11 июля 2020

Отношения «многие-ко-многим» описаны с помощью belongsToMany в 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' })

Чтобы получить документы вместе со связанными тегами, вы можете запросить следующее:

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

To добавить теги к определенному документу, вы можете вызвать метод экземпляра модели addTags:

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)
...