You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Sequelize中Op.or嵌套Op.and生成WHERE子句异常问题

Sequelize生成WHERE子句不符合预期的问题与解决

问题描述

想要生成的目标WHERE查询语句:

WHERE (x = 1 AND y = 2) OR (x = 2 AND y = 1)

在Sequelize中编写的代码:

where: {
          [Op.or]: {
            [Op.and]: {
              ownerId: candidate.recipientId,
              recipientId: candidate.senderId,
            },
            [Op.and]: {
              recipientId: candidate.recipientId,
              ownerId: candidate.senderId,
            },
          },
        },

但实际生成的查询语句却只有一组条件:

WHERE ((\"Chat\".\"recipient_id\" = 2 AND \"Chat\".\"owner_id\" = 1))

问题原因

JavaScript对象的键具有唯一性,你在Op.or的对象里重复使用了[Op.and]作为键,第二个[Op.and]会直接覆盖第一个,最终只有最后一组AND条件被保留,导致生成的SQL缺失了前半部分的判断。

正确实现方式

Sequelize要求Op.or包含多个条件分支时,使用数组形式而非对象形式。数组中的每个元素对应一组独立的AND条件(对象默认就是AND关系,可省略Op.and):

写法一(保留Op.and)

where: {
  [Op.or]: [
    {
      [Op.and]: {
        ownerId: candidate.recipientId,
        recipientId: candidate.senderId,
      }
    },
    {
      [Op.and]: {
        recipientId: candidate.recipientId,
        ownerId: candidate.senderId,
      }
    }
  ]
},

写法二(简化版)

where: {
  [Op.or]: [
    {
      ownerId: candidate.recipientId,
      recipientId: candidate.senderId,
    },
    {
      recipientId: candidate.recipientId,
      ownerId: candidate.senderId,
    }
  ]
},

两种写法都能生成符合预期的(ownerId = ? AND recipientId = ?) OR (recipientId = ? AND ownerId = ?)形式的WHERE子句。


内容的提问来源于stack exchange,提问作者愛は悪だ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 16:55:14