i have the following hierarchy of objects:
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
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.
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.
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.
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.
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
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