Retrieve Records From Multiple Tables in Sequelize
Sequelize·2 min read·Jan 1, 2025
In Sequelize, the data of associated models can essentially be fetched in two ways, through eager loading and lazy loading.
Eager loading refers to querying all the data of a model and its associated model at once, which in SQL translates to a LEFT OUTER JOIN query.
Lazy loading, on the other hand, refers to querying the data of a model, and later on, querying the data of its associated model only when you really need it.
Eager loading
In Sequelize, eager loading is done by querying a model using query methods, such as findOne() and findAll(), and specifying the associated model through the include property of the configuration object:
await ModelA.findOne|findAll({ include: { model: ModelB }});Where:
ModelAis a model instance associated with another model through thehasOne()orhasMany()method.ModelBis a model instance associated with another model through thebelongsTo()method.
This will cause the query method to return an object containing the fields of the main model, as well as the fields of the associated models.
Note: By default, Sequelize uses the name of the associated model as the name of the property under which the fields of the associated model are stored. However, in case of a one-to-many relationship, the property's name will be automatically pluralized.
Unlock the program 🚀
Pay once, own it forever.
€79
30-day money-back guarantee
- 13 modules
- 113 lessons with full-code examples
- 29 projects with commented solutions
- All future lesson and project updates
- Lifetime access
By submitting this form, you agree to the Terms & Conditions and Privacy Policy.