Gatsby.js: Filter GraphQL query by nested object property

梦想的初衷 提交于 2019-12-07 05:35:51

问题


I'm working on a news site which will have articles, each with one or multiple respective authors. If you click on an author's name, it will take you to a page displaying their information and a list of articles they have contributed to.

So each article has an authors property, which in turn is an array of author objects with properties: full name, slug (lowercase version of full name with spaces replaced by dashes), etc.

Is it possible to filter the articles by a particular author's slug when defining the query?

query authorQuery($slug: String!) {
  allContentfulArticle(filter: { //not sure what to do here }) {
    edges {
      node {
        title
        slug
        authors {
          name
          slug
        }
      }
    }
  }
}

My other option would be to load all of the articles, then setup a filter in the component like so:

const articles = data.allContentfulArticle.edges.filter(({ node }) => {
  return node.authors.some((author) => author.slug === data.contentfulAuthor.slug);
});

This wouldn't be the end of the world, however it goes against the GraphQL principle of only loading the data you need.


回答1:


What you want to achieve here if I understood correctly, you want to group articles by author. You can achieve that if you query and apply filter to allContentfulAuthor and request the article field, like so:

{
  allContentfulAuthor(filter: {slug: {eq: "myslug"}}) {
    edges {
      node {
        name
        article {
          title
          slug
        }
      }
    }
  }
}

Note that the article name is your contentTypeId for your articles.



来源:https://stackoverflow.com/questions/48532299/gatsby-js-filter-graphql-query-by-nested-object-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!