Sanity io show blog posts by author

2k views Asked by At

I'm learning Sanity io CMS and GROQ. I've build a simple blog using one the Sanity predefined blog schema. I've managed to show posts, a single post and the author page, showing name, image and bio.

What I would like to do is to show a list of the blog posts belonging to the author in his page. In the posts schema there is a reference to the author:

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

I've tried to add an array reference to post in the Author schema, but the result is that in the CMS I need to manually add posts to the author. While, I'd like to query the author and return the posts belonging to the author since there's a reference to it in the posts schema , but cannot find how to do it. Is it possibly more a GROQ query than a schema problem, or both?

3

There are 3 answers

0
Mauro74 On BEST ANSWER

Found the answer myself by looking at the Sanity documentation in the Query Cheat Sheet page. It was not a scheme problem but rather a GROQ query one. In the author page, in the query that shows the author bio etc. I've added another part in which I'm querying for the posts by that author:

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

Then I can simply map through "posts", using the "slug" to build the URL to the single post.

{author.posts &&
  author.posts.map((p) => {
    return (
      <li>
        <a href={`/post/${p.slug}`}>{p.title}</a>
      </li>
    );                  
   })
}
0
Brett DeWoody On

If you have an array of authors on a post the following syntax will retrieve all posts for the current author:

`*[_type == "author"]{
      name,
      bio,
      "authorImage": image.asset->url,
      "posts": *[_type == "post" && author._ref in authors[]->author._id ]{
        title,
        "slug": slug.current,
      }
  }`
0
Adham Tarek On

if you want to reach author by his posts, you can do this:

*[_type == "post"]{
  _id,
  title,
  author->{ // here to reach author name and image you should type ->
  name,
  image
},
description,
mainImage,
slug
}