【问题标题】:Use a beginWith or startWith filter in a graphQL query with Gatsby在 Gatsby 的 graphQL 查询中使用 begin With 或 startsWith 过滤器
【发布时间】:2020-03-19 13:00:39
【问题描述】:

按照这里的盖茨比教程https://www.gatsbyjs.org/docs/adding-tags-and-categories-to-blog-posts/,可以按标签过滤帖子以轻松创建标签页面...

我想要实现的是为具有相同 slug 前缀的帖子创建索引页面:

  • /folder1/sub1/post-A
  • /folder1/sub1/post-B
  • /folder1/sub2/post-C

将创建 3 个索引页面:

  • /folder1/(包含三个帖子)
  • /folder1/sub1/(包含帖子A和B)
  • /folder1/sub2/(仅包含帖子C)

这将使用如下查询:

export const query = graphql`
  query tagListQuery($prefix: String, $skip: Int!, $limit: Int!) {
    allMarkdownRemark(
      sort: { fields: [frontmatter___date], order: DESC }
      filter: { fields: { slug: { startsWith: $prefix } } }
      limit: $limit
      skip: $skip
    ) {
      edges {
        node {
          id
          frontmatter {
            title
          }
          fields {
            slug
          }
        }
      }
    }
  }
`

但是startsWith过滤不存在​​:

"message": "字段\"startsWith\" 未按类型定义 StringQueryOperatorInput。”

有没有办法使用与 graphQL 的前缀匹配进行过滤?

【问题讨论】:

    标签: reactjs graphql gatsby graphql-js


    【解决方案1】:

    你确定你在node 中有fields 吗?如果是这样,您应该向我们展示您的架构(在 http://localhost:8000/___graphql 中找到),例如:

    反正我猜你想查询fileAbsolutePath

    query tagListQuery($prefix: String, $skip: Int!, $limit: Int!) {
      allMarkdownRemark(sort: {order: DESC, fields: [frontmatter___date]}, fileAbsolutePath: {regex: $prefix}}, limit: $limit, skip: $skip) {
        edges {
          node {
            id
            frontmatter {
              title
            }
          }
        }
      }
    }
    

    如果要添加startWith等,需要customize the schema

    【讨论】:

    • regexp 可以解决问题,但使用起来并不是很漂亮...所以在 graphQL 中没有 startsWith 或 beginWith 运算符,或者使用自定义过滤函数扩展 graphQL 的方法?
    • 不是默认的,需要自定义gatsbyjs.org/docs/schema-customization
    猜你喜欢
    • 1970-01-01
    • 2018-04-14
    • 2021-02-08
    • 2011-05-22
    • 2020-09-11
    • 2020-09-08
    • 2020-03-23
    • 2021-02-26
    • 2019-11-22
    相关资源
    最近更新 更多