Sequelize ORM:在 and 运算符中创建一个 OR 运算符
Sequelize ORM: Make a OR operator inside and operators
我正在尝试在 Sequelize 中生成此查询:
SELECT * FROM messages
WHERE (to_user_id = 1 AND from_user_id = 2)
OR (to_user_id = 2 AND from_user_id = 1)
ORDER BY "createdAt"
我这样试试:
const messages: Messages[] = await this.messages.findAll({
where: {
[Op.or]: [
{
[Op.and]: [{ to_user_id: toUserId }, { from_user_id: fromUserId }],
[Op.and]: [{ to_user_id: fromUserId }, { from_user_id: toUserId }]
}
]
},
attributes: {
exclude: ['deletedAt']
}
});
但是正在查询:
SELECT "id", "from_user_id", "to_user_id", "body", "createdAt", "updatedAt" FROM "messages" AS "messages" WHERE ("messages"."deletedAt" IS NULL AND (("messages"."to_user_id" = 2 AND "messages"."from_user_id" = 1)))
为什么我的 OR 运算符没有被应用到这两个 and 运算符中?
您应该为 AND 条件使用单独的对象,如下所示:
const messages: Messages[] = await this.messages.findAll({
where: {
[Op.or]: [
{
[Op.and]: [{ to_user_id: toUserId }, { from_user_id: fromUserId }]
},
}
[Op.and]: [{ to_user_id: fromUserId }, { from_user_id: toUserId }]
}
]
},
attributes: {
exclude: ['deletedAt']
}
});
我正在尝试在 Sequelize 中生成此查询:
SELECT * FROM messages
WHERE (to_user_id = 1 AND from_user_id = 2)
OR (to_user_id = 2 AND from_user_id = 1)
ORDER BY "createdAt"
我这样试试:
const messages: Messages[] = await this.messages.findAll({
where: {
[Op.or]: [
{
[Op.and]: [{ to_user_id: toUserId }, { from_user_id: fromUserId }],
[Op.and]: [{ to_user_id: fromUserId }, { from_user_id: toUserId }]
}
]
},
attributes: {
exclude: ['deletedAt']
}
});
但是正在查询:
SELECT "id", "from_user_id", "to_user_id", "body", "createdAt", "updatedAt" FROM "messages" AS "messages" WHERE ("messages"."deletedAt" IS NULL AND (("messages"."to_user_id" = 2 AND "messages"."from_user_id" = 1)))
为什么我的 OR 运算符没有被应用到这两个 and 运算符中?
您应该为 AND 条件使用单独的对象,如下所示:
const messages: Messages[] = await this.messages.findAll({
where: {
[Op.or]: [
{
[Op.and]: [{ to_user_id: toUserId }, { from_user_id: fromUserId }]
},
}
[Op.and]: [{ to_user_id: fromUserId }, { from_user_id: toUserId }]
}
]
},
attributes: {
exclude: ['deletedAt']
}
});