[英]Sequelize Query to find all records that falls in between date range
我有一個帶列的模型:
from: { type: Sequelize.DATE }
to: { type: Sequelize.DATE }
我想查詢from
OR to
落在日期范圍之間的所有記錄: [startDate, endDate]
嘗試過類似的東西:
const where = {
$or: [{
from: {
$lte: startDate,
$gte: endDate,
},
to: {
$lte: startDate,
$gte: endDate,
},
}],
};
就像是:
SELECT * from MyTable WHERE (startDate <= from <= endDate) OR (startDate <= to <= endDate
對我有用的解決方案是:-
// here startDate and endDate are Date objects
const where = {
from: {
$between: [startDate, endDate]
}
};
參考了解更多關於運營商:- http://docs.sequelizejs.com/en/latest/docs/querying/#operators
注意:在MYSQL 中between
比較運算符between
是inclusive ,這意味着它等價於表達式(startDate <= from AND from <= endDate)
。
試試這個條件,我認為你要問的會這樣做。
對於續集的新版本:
const where = {
[Op.or]: [{
from: {
[Op.between]: [startDate, endDate]
}
}, {
to: {
[Op.between]: [startDate, endDate]
}
}]
};
或作為您的代碼結構:
const where = {
$or: [{
from: {
$between: [startDate, endDate]
}
}, {
to: {
$between: [startDate, endDate]
}
}]
};
有關更多信息,您可以關注此Sequelize 官方文檔
步驟 - 1需要來自 SEQUELIZE 的 Op
const { Op } = require('sequelize');
步驟 - 2聲明兩個常量:
const startedDate = new Date("2020-12-12 00:00:00");
const endDate = new Date("2020-12-26 00:00:00");
步驟 - 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}))
我同意@VigneshSundaramoorthy 的評論,即即使[Op.between]
適用於日期字符串,類型定義也表明這種用法不受官方支持。 該操作需要數字數組,並且至少在 2021 年 12 月 28 日,文檔中沒有使用Op.between
用於日期范圍的示例(僅適用於數字范圍)。
但是,我們可以以符合類型的方式實現相同的結果,這也符合 Sequelize 文檔:
const where = {
"date_field": {
[Op.and]: {
[Op.gte]: startOfDateRange,
[Op.lte]: endOfDateRange
}
}
}
這也有一點優勢,即更加明確(搜索是包容性的),而不是依賴於BETWEEN
方言行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.