I have the following models:
'use strict';
module.exports = function(sequelize, DataTypes) {
var Collection = sequelize.define("Collection", {
name: DataTypes.STRING,
customer: DataTypes.STRING
}, {
classMethods: {
associate: function(models) {
Collection.hasMany(models.Items);
}
}
});
return Collection;
};
'use strict';
module.exports = function(sequelize, DataTypes) {
var Item = sequelize.define("Item", {
itemId: {
type: DataTypes.STRING,
primaryKey: true
}
}, {
classMethods: {
associate: function(models) {
Item.belongsToMany(models.Collection);
}
}
});
return Item;
};
Lets say I want to get all the collections and their items with specific customer and one of the items contains the itemId. My query is as follows:
models.Collection.findAll({
where: {
customer: customerParam
},
include: [{
model: models.Item,
where: {
itemId: itemParam
}
}]
}).then(function(collections) {
console.log(collections);
})
The problem is that this query filters the items from the collections that I got and now they only contain the items which are with the same itemId instead of containing all the items of the collection.
To wrap up, include takes an array of objects. These objects are queries of their own, essentially just Sequelize queries within our main query. Inside each include query we specify the associated model , narrow our results with where , and alias our returned rows with as .
To change the JOIN clause from LEFT OUTER JOIN to INNER JOIN , you need to add the required: true option to the include option. Here's how you call the findAll() method to produce an INNER JOIN query: const users = await User. findAll({ include: { model: Invoice, required: true }, }); console.
Sequelize allows you to join a third table that's related to the second table by creating a nested include. For example, suppose you have three tables with the following relations: The Users table has one-to-many relation with the Invoices table. The Invoices table has many-to-one relations with the Users table.
having = Sequelize. literal(`total_due_balance = 0`); } Business // table, which you require from your defined model . findAll(searchQuery) . then(result => { console.
You get this result due to the where statements in your query are executed separately like subqueries.
So, if you want to generate where clause like it WHERE Collection.customer = 'blabla' AND Item.itemId = 1
you should do the following:
models.Collection.findAll({
where: {
customer: customerParam,
'$items.itemId$': itemParam
},
include: [{
model: models.Item,
as: 'items'
}]
})
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