I'm using Sequelize and I have 2 models (Article and Tag) associated with belongsToMany through another model called ArticleTags.
I want to fetch all the Articles that have one Tag with id=1 AND one Tag with id=2.
I've tried multiple solutions, but it always fetches the Articles that have one Tag with id=1 OR one Tag with id=2.
This is the code I have as of now:
let articles = await Article.findAll({
limit: limit,
offset: offset,
subQuery: false,
where:[ {"$Tags.id$": {1,2} }]
include:{
model: Tag,
required: false
},
});
Change your where clause to this:
where: {
"$Tags.id$": {
[Op.and]: [1, 2]
}
}
// SELECT * FROM articles WHERE $Tags.id$ = 1 AND $Tags.id$ = 2
This should work else have another look at the docs for applying where clauses