How to perform nested include ? I have table products that has one to many relation with comments, and table comments has many to one relation with users table. So comments has user_id, and product_id. My code is like this
var models = require('../models'); models.products.findAll({ include: [ {model: models.comments} ] }).then(function (products) { next(products); }).catch(function (err) { next(err); }); });
I get the comments, but I would like to have something like
models.products.findAll({ include: [ {model: models.comments.include(models.comments.users)} ] })
Is this possible without writing custom queries ?
You can modify the query to use INNER JOIN by adding a where condition inside the include option. The following JavaScript code: const data = await User. findAll({ include: [{ model: Invoice, include: [{ model: City, where: { id: 1 } }] }], }); console.
Your solution, along with using include: {all:true} in my findAll query, did the trick. instead of using include: {all:true} in findAll you can use include: {model: models. User, as: 'createdByUser'} , etc. Be sure to use as: in all associations to the same model in your Sequelize model declaration.
Sequelize eager loading is a way to fetch data from multiple tables that have relations between each other. When you use the eager loading technique, the generated SQL query will have one or more JOIN clauses.
models.products.findAll({ include: [ {model: models.comments, include: [models.comments.users] } ] })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With