可爱的 Sequelize JS 遇到更多麻烦。
我正在尝试将以下查询放入 Sequelize 范围中。
SELECT *
FROM Projects
WHERE isDeleted IS NOT true
AND (
( importSource IS NOT null ) AND ( createdAt BETWEEN '2018-01-19' AND '2018-01-29')
OR
( importSource IS null ) AND ( createdAt > '2018-01-19' )
)
目前在我的模型中尝试此操作无济于事。
scopes: {
active: {
where: {
isDeleted: {
[Op.not]: true
},
[Op.or]: [
{
importSource: { [Op.ne]: null },
createdAt: {
[Op.between]: [
new Date(new Date() - 30 * ( 24 * 60 * 60 * 1000)),
new Date(new Date() - 4 * (24 * 60 * 60 * 1000))
],
}
},
{
importSource: { [Op.eq]: null },
createdAt: {
[Op.gt]: new Date(new Date() - 30 * ( 24 * 60 * 60 * 1000)),
}
}
]
}
}
}
没有错误。这就是正在运行的以下 MySQL。
Executing (default): SELECT `id`, `url`, `title`, `company`, `importSource`, `importSourceId`, `publishedAt`, `createdAt`, `updatedAt` FROM `Projects` AS `Project` WHERE `Project`.`isDeleted` IS NOT true ORDER BY `Project`.`id` DESC LIMIT 5;
这是调用模型和范围的 Controller 方法。
exports.index = (req, res) => {
const MAX = 50;
var numberProjects = ((req.query.number) ? req.query.number : MAX);
numberProjects = ((numberProjects > MAX) ? MAX : numberProjects);
Project.scope('active').findAll({
order: [
['id', 'DESC']
],
limit: +numberProjects
})
.then( projects => {
res.send( projects );
})
};
感谢任何帮助。
最佳答案
在提出这个问题后 20 分钟就解决了这个问题。
将 [Op.or]
更改为 $or
似乎有效。
scopes: {
active: {
where: {
isDeleted: { [Op.not]: true },
$or: [
{
importSource: { [Op.ne]: null },
createdAt: {
[Op.between]: [
new Date(new Date() - 30 * ( 24 * 60 * 60 * 1000)),
new Date(new Date() - 4 * (24 * 60 * 60 * 1000))
],
}
},
{
importSource: { [Op.eq]: null },
createdAt: {
[Op.gt]: new Date(new Date() - 30 * ( 24 * 60 * 60 * 1000)),
}
}
]
}
}
}
关于javascript - 在 Sequelize js 的范围内同时使用 "AND"和 "OR",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48736603/