使用GROQ(合理性)过滤日期(日期时间)数组(React App)

时间:2019-08-15 12:54:05

标签: sanity groq

我列出了可以多次显示的电影。我决定为用户提供一个选项,可以为一部电影选择多个日期(sanity studio界面)。

电影的架构如下:

export default {
  name: 'movie',
  title: 'Movie',
  type: 'document',
  fields: [
    {
      name: 'title',
      title: 'Title',
      type: 'string'
    },
    {
      name: 'dates',
      title: 'Dates',
      type: 'array',
      of: [
        {
          type: 'datetime',
          options: {
            dateFormat: 'YYYY-MM-DD',
            timeFormat: 'HH:mm',
            timeStep: 15,
            calendarTodayLabel: 'Today'
          }
        }
      ]
    },
    {
      name: 'poster',
      title: 'Poster',
      type: 'image',
      options: {
        hotspot: true
      }
    },
    {
      name: 'body',
      title: 'Body',
      type: 'blockContent'
    }
  ],

  preview: {
    select: {
      title: 'title',
      date: 'date',
      media: 'poster'
    }
  }
}

当前查询:

const query = groq`*[_type == "movie"]{
  title,
  dates,
  poster,
  body
}`

我需要使用GROQ过滤在date数组中具有今天日期的电影

也许我把这个复杂化了,有人会想出更好的方法。

这个想法是为了避免数据库中出现重复(1部电影可以显示3到6次)。那是我使用数组的唯一原因

1 个答案:

答案 0 :(得分:0)

解决方案应该是:

const query = '*[_type == "movie" && dates match $today]{title, dates, poster, body}'
const today = new Date().toISOString().split('T')[0]
client.fetch(query, {today}).then(result => {
  // movies which are showing today
})

但是,字符串标记程序中当前存在一个错误,该错误会破坏日期字符串匹配。同时,恐怕您唯一的选择是获取所有电影并筛选客户端。我们希望尽快解决此问题。