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,提问作者愛は悪だ
相关产品推荐
相关产品推荐

