给出这样的架构:
posts
- id
- userId
postTags
- id
- postId
- type
- value
在Sequelize中设置
Posts.hasMany(PostTags(sequelize), { as: 'tags', foreignKey: 'postId' });
为了进行过滤,我们需要对不同标签类型/值的组合进行动态查询。这是我想要生成的SQL类型:
select posts.* from posts
inner join postTags pt1 on pt1.postId = posts.id and
pt1.type = 'language' and pt1.value = 'javascript'
inner join postTags pt2 on pt2.postId = posts.id and
pt2.type = 'library' and pt2.value = 'Sequelize.js'
...
inner join postTags ptN on ptN.postId = posts.id and
ptN.type = 'sentiment' and ptN.value = 'happy'
where posts.userId = 123;
随着标签表中类型数量的增加,我们需要加入同一个表的次数会随着时间的推移而增加,所以只设置多个hasMany关联是不合适的。
有没有办法用Sequelize做到这一点,还是我需要放入原始SQL?