Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested include in sequelize?

Tags:

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 ?

like image 776
ihoryam Avatar asked Nov 26 '15 15:11

ihoryam


People also ask

How do you use include inside include in Sequelize?

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.

How do you include two models in Sequelize?

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.

What is eager loading Sequelize?

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.


1 Answers

models.products.findAll({   include: [     {model: models.comments, include: [models.comments.users] }   ] })  
like image 175
Jan Aagaard Meier Avatar answered Sep 17 '22 11:09

Jan Aagaard Meier