本文介绍了如何在 gatsby graphql 中查询日期范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在graphql中有这个查询.但是大于(gt) 和小于(lt) 不是定义的字段.

So i have this query in graphql. But greater than(gt) and less than(lt) is not a defined field.

query Test {
  allStrapiEvent(filter:{date:{gt:"02/13/2019"}}){
    edges{
      node{
        name
        date(formatString:"MM/DD/YYYY")
      }
    }
  }
}

推荐答案

看起来 dateString 类型的,因此没有得到比较运算符 (gt, lt, gte, lte);真可惜,因为这真的很有用.

It looks like date is of String type, and therefore doesn't get the comparison operators (gt, lt, gte, lte); which is a shame, because this is really useful.

我认为作为一种解决方法,您可以添加一个附加字段,例如 timestamp 并将日期存储在数字中(如果您的 CMS 尚未提供).然后您可以对它们使用比较运算符.

I think as a workaround, you can add an additional field like timestamp and store the date in number (if not already provided by your CMS). Then you can use comparison operators on them.

// moment.js comes with gatsby
const moment = require('moment');

exports.onCreateNode = ({ node, actions }) => {
  const { createNodeField } = actions

  // I'm guessing your type is StrapiEvent, but it could be st else
  if (node.internal.type === `StrapiEvent`) {
    const date = node.date;

    createNodeField({
      name: 'timestamp',
      node,
      // convert date to unix timestamp & convert to number
      value: +moment(date).format('X'),
    })
  }
}

然后说您想获取从昨天开始的事件.你可以像 moment().subtract(1, 'day').format('X')//1549044285

Then say you want to get events starting from yesterday. You can get the unix timestamp like moment().subtract(1, 'day').format('X') // 1549044285

query Test {
  allStrapiEvent(filter: {
    fields: {
      timestamp: {
        gt: 1549044285
      }
    }
  }) {
    edges{
      node{
        name
        date(formatString:"MM/DD/YYYY")
      }
    }
  }
}

不理想,但会起作用.

这篇关于如何在 gatsby graphql 中查询日期范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 03:16