Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

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

I am trying to fetch data from Contentful with a filter whose eq operator is also fetched from Contentful. In my current scenario, as shown in the code below, I am trying to filter the content fetched from allContentfulPost with the value fetched from label in contentfulCategory.

Any ideas how I can do so? I tried using $label in the allContentfulPost filter eq operator, but that didn't work.

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
            }
          }
        }
      }
    }
  }
`

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Contentful DevRel here. ??

Can you try the following query? :)

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
            }
          }
        }
      }
    }
  }
`

You can filter for $slug in allContentfulPost, too. With the query above you're requesting two different resources:

  1. the one category matching the $slug as contentfulCategory

  2. posts that are linking to a category that matched the correct $slug as allContentfulPost


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...