I am trying to querying a join table using sequelize: Here is the model:
db.client.belongsToMany(db.user, {
through: db.clientUser,
onDelete: 'cascade',
});
db.user.belongsToMany(db.client, {
through: db.clientUser,
});
and this is what I am trying to do:
db.user.findAll({
where: {
group_id: 1,
},
include: [{
model: db.clientUser,
where: {
is_manager: 1,
}
}],
raw: true,
})
However I get the following error: client_user is not associated to user!
Any idea what could be the cause of this issue?
There are two ways you can create JOIN queries and fetch data from multiple tables with Sequelize: Create raw SQL query using sequelize. query() method. Associate related Sequelize models and add the include option in your Sequelize query method.
Join Two or More Tables You can combine rows from two or more tables, based on a related column between them, by using a JOIN statement.
To make join queries using Sequelize on Node. js, we can use the include option with findAll . const posts = await Posts. findAll({ include: [{ model: User, required: true }] }) //...
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 .
You declared a relationship between client
from user
through clientUser
. Although pedantic, its complaint is technically correct: there is no explicitly declared relationship declared between client
and clientUser
. Nor should there be: your belongsToMany
relationship should take care of that. Your query can be adjusted to work with this relationship.
Note: I don't know what tables group_id and is_manager are found in. They may need to be shuffled around.
db.user.findAll({
where: {
group_id: 1,
},
include: [{
model: db.client,
through: {
where: {
is_manager: 1, // Assuming clientUser.is_manager?
},
}],
raw: true,
})
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