我有三个模型 - Book
、User
和 Institution
- 它们相互关联,如下所示:
书籍通过
Book_Institution
连接表与机构关联(多对多关系)Book.belongsToMany(models.Institution, { through: 'Book_Institution' })
和
Institution.belongsToMany(models.Book, { through: 'Book_Institution' })
用户可以通过两种方式与机构关联:作为读者或作者。这是通过两个连接表完成的:
Author_Institution
和Reader_Institution
:Institution.belongsToMany(models.User, { through: 'Author_Institution' }) Institution.belongsToMany(models.User, { through: 'Reader_Institution' })
和
User.belongsToMany(models.Institution, { through: 'Author_Institution' }) User.belongsToMany(models.Institution, { through: 'Reader_Institution' })
(为了简洁起见,每次都省略
foreignKey
。)
我想查询 Book
模型以查找属于某个作者的所有书籍。 Sequelize 提供 include
选项来轻松连接两个关联的表。我遇到的问题是,使用如下所示的 include
默认为 Reader_Institution
关联。我如何指定应使用哪个关联?
getBooks: (obj, args, context) => {
const { user } = context
return Book.findAll({
attributes: ['id', 'path'],
include: [{
include: [{
attributes: ['id'],
model: User,
where: { id: user }
}],
model: Institution,
required: true // inner join
}]
})
}
预先感谢您的帮助。
最佳答案
我使用 as
,它允许您通过该别名引用关系。
Institution.belongsToMany(models.User, {
through: 'Author_Institution', // many-to-many relationship table name
as: 'AuthorInstitution' // alias
})
以这种方式设置模型后,您可以使用 as
来指定查询时要包含的关系。
getBooks: (obj, args, context) => {
const { user } = context
return Book.findAll({
attributes: ['id', 'path'],
include: [{
include: [{
attributes: ['id'],
model: User,
where: { id: user },
as: 'AuthorInstitution'
}],
model: Institution,
required: true // inner join
}]
})
}
此外,通过这种方法,您可以通过 as
引用关系数据,因此您可以执行 book.AuthorInstitution
,它将是那个对象。
关于javascript - 如何消除 Sequelize 中相同模型之间的多个关联之间的歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48647236/