我有多个相互关联的表,现在我想做的是在Document and Tag
之间创建一个多对多关系。
一个文档可以有多个标签,一个标签可以有多个文档。我如何在sequelize中实现这种许多关系?
在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
参数,但我不明白它是如何工作的
在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' })
要获得带有链接标签的文档,您可以这样查询:
const docs = await database.Document.findAll({
where: {
// here are your search conditions
},
include: [database.Tag]
})
要向某个文档添加标记,可以调用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)