我有三个模型-Book
,User
和机构
-它们彼此关联如下:
>
Book.belongsToMany(models.Institution, { through: 'Book_Institution' })
和
Institution.belongsToMany(models.Book, { through: 'Book_Institution' })
用户可以通过两种方式与机构关联:作为读者或作者。这是通过两个联接表完成的:Author\u Institution
和Reader\u 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
)
我想查询图书
模型以查找属于作者的所有图书。Sequelize提供了include
选项,可以轻松地联接两个关联的表。我遇到的问题是,使用如下所示的include
默认为Reader\u 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
}]
})
}
提前感谢你的帮助。
我使用作为
,它允许您通过该别名引用关系。
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
}]
})
}
此外,使用这种方法,它允许您通过作为
引用关系数据,因此您可以编写书。它将是该对象的值。