Ano*_*bie 27 mysql sequelize.js
我有一个带列的模型:
from: { type: Sequelize.DATE }
to: { type: Sequelize.DATE }
Run Code Online (Sandbox Code Playgroud)
并且想要查询fromOR to落在日期范围之间的所有记录:[startDate, endDate]
我尝试过类似的东西:
const where = {
$or: [{
from: {
$lte: startDate,
$gte: endDate,
},
to: {
$lte: startDate,
$gte: endDate,
},
}],
};
Run Code Online (Sandbox Code Playgroud)
类似于:来自MyTable WHERE的SELECT*(startDate <= from <= endDate)或(startDate <= to <= endDate
Aks*_*ngh 40
对我有用的解决方案是: -
# here startDate and endDate are Javascript Date object
const where = {
from: {
$between: [startDate, endDate]
}
};
Run Code Online (Sandbox Code Playgroud)
有关运营商的更多信息,请参阅:http://docs.sequelizejs.com/en/latest/docs/querying/#operators
注意:
在MYSQL中, between比较运算符是包含的,这意味着它等同于表达式(startDate <= from AND from <= endDate).
M.A*_*pon 15
试试这个条件,我认为你要问的会这样做。
对于续集的新版本:
const where = {
[Op.or]: [{
from: {
[Op.between]: [startDate, endDate]
}
}, {
to: {
[Op.between]: [startDate, endDate]
}
}]
};
Run Code Online (Sandbox Code Playgroud)
或作为您的代码结构:
const where = {
$or: [{
from: {
$between: [startDate, endDate]
}
}, {
to: {
$between: [startDate, endDate]
}
}]
};
Run Code Online (Sandbox Code Playgroud)
有关更多信息,您可以关注此Sequelize 官方文档
我同意 @VigneshSundaramoorthy 的评论,即即使[Op.between]适用于日期字符串,类型定义也表明这种用法不受官方支持。该操作需要数字数组,并且至少截至 2021 年 12 月 28 日,文档没有使用Op.between日期范围的示例(仅适用于数字范围)。
但是,我们可以通过类型兼容的方式实现相同的结果,这也与 Sequelize 文档一致:
const where = {
"date_field": {
[Op.and]: {
[Op.gte]: startOfDateRange,
[Op.lte]: endOfDateRange
}
}
}
Run Code Online (Sandbox Code Playgroud)
这还有一个小小的优点,那就是更加明确(搜索是包容性的),而不是依赖于BETWEEN.
小智 6
步骤 - 1 需要来自 SEQUELIZE 的 Op
const { Op } = require('sequelize');
Run Code Online (Sandbox Code Playgroud)
步骤 - 2 声明两个常量:
const startedDate = new Date("2020-12-12 00:00:00");
const endDate = new Date("2020-12-26 00:00:00");
Run Code Online (Sandbox Code Playgroud)
步骤 - 3
table.findAll({where : {"fieldOfYourDate" : {[Op.between] : [startedDate , endDate ]}}})
.then((result) => res.status(200).json({data : result}))
.catch((error) => res.status(404).json({errorInfo: error}))
Run Code Online (Sandbox Code Playgroud)