Reputation: 71
I have a User
model, a Message
model and a Group
model. Message belongsTo Group
, Group belongsToMany User(group_members, { as: 'members' })
I want to query all messages where a particular user is a member of its group. I achieved this with an include
on Message
like so:
include: [ {
model: Group,
include: {
association: 'members',
where: {
id: userId
}
},
required: true
} ]
However this returns Message.Group.members
as an array of only the user I checked for. This is of course expected but what would I do if I want all the members (where userId
is one of them)?
EDIT - This seems to be what I'm looking for.
Upvotes: 0
Views: 225
Reputation: 2447
Your where condition should be outside of the include. With the required creating an inner join, you can filter the results like that :
models.Message.findAll({
attributes: [ 'idcustomer', 'firstname', 'lastname' ],
include: [ {
model: Group,
include: {
association: 'members'
}
} ]
where: {
'group.members.id': userId
}
});
This should work.
Upvotes: 1