How To Disambiguate Between Multiple Associations Between The Same Models In Sequelize
I have three models — Book, User and Institution — which are associated to one another as follows: Books are associated to Institutions via a Book_Institution join table (many
Solution 1:
I use as
which allows you to reference the relationship through that alias.
Institution.belongsToMany(models.User, {
through: 'Author_Institution', // many-to-many relationship table nameas: 'AuthorInstitution'// alias
})
With your models set up this way, you can use as
to to specify which relationship you want to include when querying.
getBooks:(obj,args,context)=> {
const { user } =contextreturnBook.findAll({
attributes: ['id', 'path'],
include: [{
include: [{
attributes: ['id'],
model:User,
where: { id:user },
as:'AuthorInstitution'
}],
model:Institution,
required:true//innerjoin
}]
})
}
Also, with this methodology, it allows you you to reference the relationship data via the as
, so you can do book.AuthorInstitution
and it will be the value of that object.
Post a Comment for "How To Disambiguate Between Multiple Associations Between The Same Models In Sequelize"