Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs + sequelize :: include where required false

i have the following hierarchy of objects:

  1. user
  2. parent (hasOne)
  3. children (hasMany)

once i have a user object, im attempting to load the associated parent object along with some of its children. the following works:

user.getParent({
  include: [{
    model: Child
  }]
}).then(function(parent) {
  var children = parent.children;
});

but if i want to selectively load some of the parent's children, like so:

user.getParent({
  include: [{
    model: Child,
    where: { gender: 'FEMALE' }
  }]
}).then(function(parent) {
  var daughters = parent.daughters;
});

if the parent has one or more daughters, the query works and i get the parent data along with all daughters' data. however, if the parent has only sons, the parent object returned is null..

i want that if the parent has no daughters, the parent object should still be resolved with children = null or children = []..

also, if i wanted to simply load a count of children while loading the parent, how can i go about doing that?

thanks

like image 599
AweSIM Avatar asked Jun 27 '15 17:06

AweSIM


People also ask

What is required false in Sequelize?

sequelize fails to load a model if a nested include has a where clause that returns no models.. to ensure it doesnt fail completely, you can set a required: false clause along with the where clause.. this makes sequelize return a blank array instead of failing the load completely.. Save this answer.

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 make a field required in Sequelize?

If you're using Sequelize, the equivalent of required: true on mongoose is just allowNull: false . You'd write something along these lines: const YourTable = sequelize. define('your_table', { firstname: { type: Sequelize.

What is required true in Sequelize?

This is the case because, when the where option is used inside an include , Sequelize automatically sets the required option to true . This means that, instead of an OUTER JOIN , an INNER JOIN is done, returning only the parent models with at least one matching children.


1 Answers

it turned out to be an issue with my own code.. sequelize fails to load a model if a nested include has a where clause that returns no models.. to ensure it doesnt fail completely, you can set a required: false clause along with the where clause.. this makes sequelize return a blank array instead of failing the load completely..

more info at https://github.com/sequelize/sequelize/issues/4019

like image 72
AweSIM Avatar answered Oct 17 '22 11:10

AweSIM