1

我正在学习 Sanity io CMS 和 GROQ。我使用 Sanity 预定义的博客模式构建了一个简单的博客。我已经设法显示帖子、单个帖子和作者页面,显示名称、图像和简历。

我想做的是在他的页面中显示属于作者的博客文章列表。在帖子架构中有对作者的引用:

{
  name: 'author',
  title: 'Author',
  type: 'reference',
  to: {type: 'author'},
},

我试图post在作者模式中添加一个数组引用,但结果是在 CMS 中我需要手动向作者添加帖子。同时,我想查询作者并返回属于作者的帖子,因为帖子架构中有对它的引用,但找不到如何去做。它可能更像是一个 GROQ 查询而不是模式问题,还是两者兼而有之?

4

2 回答 2

1

通过查看查询备忘单页面中的健全性文档自己找到了答案。这不是方案问题,而是 GROQ 查询问题。在作者页面中,在显示作者简介等的查询中。我添加了另一部分,其中我正在查询该作者的帖子:

// GROQ Query
sanityClient
  .fetch(
    `*[_type == "author"]{
      name,
      bio,
      "authorImage": image.asset->url,
      "posts": *[_type == "post" && author._ref in *[_type=="author" && name == name ]._id ]{
        title,
        "slug": slug.current,
      }
  }`
  )
  .then((data) => setAuthor(data[0]))
  .catch(console.error);

然后我可以简单地映射通过“帖子”,使用“slug”来构建单个帖子的 URL。

{author.posts &&
  author.posts.map((p) => {
    return (
      <li>
        <a href={`/post/${p.slug}`}>{p.title}</a>
      </li>
    );                  
   })
}
于 2021-05-04T09:02:21.573 回答
0

如果你想通过他的帖子联系作者,你可以这样做:

*[_type == "post"]{
  _id,
  title,
  author->{ // here to reach author name and image you should type ->
  name,
  image
},
description,
mainImage,
slug
}
于 2022-02-15T15:34:43.083 回答