【发布时间】:2018-02-06 16:08:58
【问题描述】:
我有三个模型 — 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
}]
})
}
提前感谢您的帮助。
【问题讨论】:
标签: javascript join sequelize.js