【问题标题】:AND Condition on belongsToMany association SEQUELIZEbelongsToMany 关联 SEQUELIZE 的 AND 条件
【发布时间】:2022-01-08 22:38:07
【问题描述】:

我正在使用 Sequelize,我有 2 个模型(文章和标签)通过另一个名为 ArticleTags 的模型与 belongsToMany 相关联。

我想获取所有包含一个 id=1 的标签和一个 id=2 的标签的文章。

我尝试了多种解决方案,但它总是获取具有一个 id=1 的标签或一个 id=2 的标签的文章。

这是我目前拥有的代码:

let articles = await Article.findAll({
    limit: limit, 
    offset: offset, 
    subQuery: false,
    where:[ {"$Tags.id$": {1,2} }]


    include:{
        model: Tag, 
        required: false
    }, 

});

【问题讨论】:

    标签: javascript node.js orm sequelize.js sequelize-typescript


    【解决方案1】:

    将 where 子句更改为:

    where: {
      "$Tags.id$": {
        [Op.and]: [1, 2]
      }
    }
    // SELECT * FROM articles WHERE $Tags.id$ = 1 AND $Tags.id$ = 2
    

    这应该可以,否则再看看docs for applying where clauses

    【讨论】:

    • 嘿!感谢您的回复,但我认为这不起作用。
    • 它返回一个空列表,我假设如果 id = 1 AND id = 2,它会检查相同的标签,这将是错误的。
    • 这是您建议的更改的 raq SQL:
    • SELECT Article.id, Tags.id AS Tags.id, Tags.text AS Tags.text, Tags->ArticleTagAS@.@8 987654333,Tags->ArticleTag 987654336 @ Articles Articles Article左外连接(@ 98765439 @ Inner join Tags Tags 987654343 id = Tags->ArticleTag.TagId) 开启 Article.id = Tags->ArticleTag.ArticleId 在哪里 ((Tags.id = 1 AND Tags.@98765434) /跨度>
    猜你喜欢
    • 2017-08-15
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多