abhisek mishra
abhisek mishra

Reputation: 49

How to perform chaining in sequelize association?

Suppose i have 3 models.

Model 1: (author)

hasMany: books

Model 2: (book)

belongsTo: author

hasOne: category

foreign key: authorId

Model 3: (category)

belongsTo: book

foreign key: bookId

Now if i do,

author.findOne(where: {id: 1}, include: "books")
//then for author having id 1 i get all respective books

But i want the category as well for all the books. So is there any way i can chain further the book model to get the desired results.

Upvotes: 0

Views: 264

Answers (1)

hawschiat
hawschiat

Reputation: 346

On Sequelize v6, you can perform a nested eager loading as follows:

author.findOne({
  where: {id: 1},
  include: {
    model: Book,
    include: {
      model: Category
    }
  }
})

Note that Book and Category are model instances.

Upvotes: 1

Related Questions