问题描述
我正在一个新闻网站上工作,该网站上将有文章,每篇文章都有一个或多个各自的作者.如果单击作者的姓名,它将带您到一个页面,显示他们的信息和他们贡献的文章列表.
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.
在定义查询时是否可以按特定作者的文章过滤文章?
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查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!