sanitygroq

Sanity io show blog posts by author


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?


Solution

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