DEV Community

Cover image for Get results and total count of Sanity records by GROQ
Ayyash
Ayyash

Posted on

10 3

Get results and total count of Sanity records by GROQ

To retrieve the results and the total, using GROQ for Sanity.IO, you need to start by casting to your model like this (this is passed in query)

query = `{
    "items": *[_type == "post"] | order(publishedAt desc)[1...5],
     "total": count(*[_type == "post"]) 

}`
Enter fullscreen mode Exit fullscreen mode

The result looks like this

{
    "ms": 65,
    "query": "...",
    "result": {
        "items": [
            {...}
        ],
        "total": 34
    }
}
Enter fullscreen mode Exit fullscreen mode

It looks obvious, but I had to read How Queries Work all the way to the end to figure out I can project my own outside model. Hope this helps someone.

RESOURCES

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more