Sequelize查询包含和逻辑

时间:2018-04-14 19:47:37

标签: sequelize.js

我有三个表:ArticleTagArticleTag。一篇文章可以有多个标签,标签可以通过ArticleTag属于多篇文章。 Tag有一个name属性。

我想查询所有包含标记tag1和(tag2tag3)和(tag4tag5)的文章。 以下查询不起作用。

Article.findAll({
    where: {},
    include: [
        { 
            model: Tag,
            where: {
                [Op.and]: [
                  { name: 'tag1' },
                  { name: { [Op.or]: ['tag2', 'tag3'] } },
                  { name: { [Op.or]: ['tag4', 'tag5'] } },
                ] 
            }
        }
    ]
})

1 个答案:

答案 0 :(得分:1)

我认为havinggroup_by会为您提供预期的结果(请在下面的代码中阅读评论):

Article.findAll({
    where: {},
    include: [
        { 
            model: Tag,
            where: {
                [Op.or]: [ { name: 'tag1' }, { name: 'tag2' }] // change from and to or 
            }
        }
    ]
    group : ['articles.id','tags.id'] , // might need to change table name as per yours
    having : {
        db.sequelize.where(db.sequelize.fn('count', db.sequelize.fn('DISTINCT', db.sequelize.col('articles.id'))),2)                    
    }
});

对于更新的问题,只需在以下位置更改或阻止:

[Op.and]: [
    { name: 'tag1' },
    { name: { [Op.or]: ['tag2', 'tag3'] } },
    { name: { [Op.or]: ['tag4', 'tag5'] } },
]