如何使用从 Gatsby 中的 Contentful 获取的值过滤从 Contentful 获取的数据?

How can I filter data fetched from Contentful using a value also fetched from Contentful in Gatsby?

我正在尝试使用过滤器从 Contentful 获取数据,该过滤器的 eq 运算符也是从 Contentful 获取的。在我当前的场景中,如下面的代码所示,我正在尝试使用从 contentfulCategory.

中的 label 获取的值来过滤从 allContentfulPost 获取的内容

有什么办法可以做到吗?我尝试在 allContentfulPost 过滤器 eq 运算符中使用 $label,但这没有用。

export const pageQuery = graphql`

  query CategoryBySlug($slug: String!) {

    contentfulCategory (slug: { eq: $slug }) {
      slug
      label
    }

    allContentfulPost (filter: { categories: { elemMatch: { label: { eq: ????? } } } }) {
      edges {
        node {
          title
          slug
          featured
          image {
            fluid {
              src
            }
          }
        }
      }
    }
  }
`

此处内容丰富的 DevRel。

你能试试下面的查询吗? :)

export const pageQuery = graphql`
  query CategoryBySlug($slug: String!) {
    contentfulCategory (slug: { eq: $slug }) {
      slug
      label
    }

    allContentfulPost (filter: { 
      categories: { 
        elemMatch: { 
          slug: { 
            #  reuse the $slug argument to filter the related articles 
            eq: $slug
          }
        }
      }
    }) {
      edges {
        node {
          title
          slug
          featured
          image {
            fluid {
              src
            }
          }
        }
      }
    }
  }
`

您也可以在 allContentfulPost 中筛选 $slug。通过上面的查询,您请求两种不同的资源:

  1. 匹配$slug的一类为contentfulCategory

  2. 链接到与正确 $slug 匹配的类别的帖子 allContentfulPost