Gatsby.js:按嵌套对象属性过滤 GraphQL 查询 [英] Gatsby.js: Filter GraphQL query by nested object property

查看:28
本文介绍了Gatsby.js:按嵌套对象属性过滤 GraphQL 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个新闻网站上工作,该网站将有文章,每篇文章都有一个或多个作者.如果您点击作者的姓名,它会将您带到一个页面,其中显示了他们的信息和他们贡献的文章列表.

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.

所以每篇文章都有一个 authors 属性,它又是一个 author 对象的数组,这些对象具有以下属性:全名、slug(全名的小写版本用破折号代替空格)等

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.

是否可以在定义查询时通过特定作者的 slug 过滤文章?

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);
});

这不会是世界末日,但它违背了仅加载您需要的数据的 GraphQL 原则.

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

推荐答案

如果我理解正确,你想在这里实现什么,你想按作者对文章进行分组.如果您查询并将过滤器应用于 allContentfulAuthor,您可以实现这一点并请求 article 字段,如下所示:

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

请注意,article 名称是您文章的 contentTypeId.

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

这篇关于Gatsby.js:按嵌套对象属性过滤 GraphQL 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆