You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Sequelize对接Postgres如何实现日期筛选为空时返回全部数据

实现方案

你可以动态构建查询条件数组,仅当日期参数为有效值(非null、非空字符串)时才把对应筛选规则加入查询条件,无效参数直接跳过即可。

修改后代码示例

// 先初始化AND条件数组
const andConditions = []

// 仅当fromDate有效时添加起始日期筛选
if (fromDate && fromDate.trim() !== '') {
  andConditions.push({
    start_date: {
      [Op.gte]: fromDate
    }
  })
}

// 仅当toDate有效时添加结束日期筛选
if (toDate && toDate.trim() !== '') {
  andConditions.push({
    end_date: {
      [Op.lte]: toDate
    }
  })
}

call.findAll({
  include: [{
    all: true,
    nested: true
  }],
  order: [
    ['start_date', 'DESC']
  ],
  where: {
    [Op.and]: andConditions
  }
})

原理解释

  • 当两个日期参数都无效时,andConditions为空数组,Sequelize会自动忽略Op.and条件,不会添加任何日期过滤规则,返回所有符合其他隐含条件的行
  • 如果只有其中一个参数有效,只会添加对应日期的筛选规则,另一个维度不做限制
  • 如果你需要兼容参数可能是undefined的场景,只需要在判断条件里新增对应的校验逻辑即可

内容的提问来源于stack exchange,提问作者Tayyab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 00:51:03