Given the following Sequelize models:
models.Post.belongsToMany(models.Tag, {
through: models.PostTag,
foreignKey: 'post_id',
as: 'tags'
});
models.Tag.belongsToMany(models.Post, {
through: models.PostTag,
foreignKey: 'tag_id'
});
I am able to query for all posts tagged with the tag having tag_id = 2 like this:
models.Post.findAll({
include: [{
model: models.Tag,
as: 'tags',
where: {
tag_id: 2
}
}]
})
Now, I would like to query for all posts that have been tagged with all of the following tags (tag_id): 2, 5, 17, 87 (or any other set of tags). I am using MySQL as DB dialect.
In SQL this can be accomplished with a series of inner joins, but is it possible with Sequelize?
select p.* from (Posts p INNER JOIN PostTags pt ON p._id=pt.post_id INNER JOIN Tags t ON pt.tag_id=t._id AND t._id=1)
INNER JOIN (Posts p1 INNER JOIN PostTags pt1 ON p1._id=pt1.post_id INNER JOIN Tags t1 ON pt1.tag_id=t1._id AND t1._id=3) ON p._id = p1._id
INNER JOIN (Posts p2 INNER JOIN PostTags pt2 ON p2._id=pt2.post_id INNER JOIN Tags t2 ON pt2.tag_id=t2._id AND t2._id=6) ON p._id = p2._id;for (var i = 0; i < 10; i++) { models.Post.belongsToMany(models.Tag, { through: models.PostTag, foreignKey: 'post_id', as: 'tags' + i }); models.Tag.belongsToMany(models.Post, { through: models.PostTag, foreignKey: 'tag_id', as: 'tags' + i });}models.Post.findAll({ include: [{ model: models.Tag, as: 'tags0', where: { _id: 2 } }, { model: models.Tag, as: 'tags1', where: { _id: 5 } }, { model: models.Tag, as: 'tags2', where: { _id: 17 } }]})