我有三种模型-- 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,{透:'Author_Institution‘}) Institution.belongsToMany(models.User,{透:'Reader_Institution’})
和
User.belongsToMany(models.Institution,{透:'Author_Institution‘}) User.belongsToMany(models.Institution,{透:'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
}]
})
}提前谢谢你的帮助。
发布于 2018-02-06 16:27:35
我使用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,它将是该对象的值。
https://stackoverflow.com/questions/48647236
复制相似问题