How to show Referenced Object with Groq

891 views Asked by At

I have a "Success cases" page (/cases) where when I go into the detail page I have something like /cases/some-slug.

The "cases" schema is referencing to a Brand, like this:


    {title: 'Case Brand', name: 'caseBrand', type: 'reference',
            to: [
                {type: 'brands'}
            ]
     },

In all the examples I've found, I have to link the brand to the cases. But it's more useful if I link each case to a specific brand. (The other way I have to attach to the brand, multiple cases).

So, the Example below I did the oposite way (which is not convenient for the structure I've build):

    const getCaseBrand = `*[_type=="cases" && caseSlug.current == "${slug}" ]{
            _id,caseSlug,
            "brand": *[_type =="brands" && references(^._id)]{ 
                _id,
                brandName,
                brandDescription,
                brandLogo
              }
    }`;

Any idea how can I build the way I need? Basically it's:

  • Get the caseBrand object, based on the reference from "cases" schema.
  • This I will show the Brand Name & Logo in Individual Case page.

Thank you so much.

1

There are 1 answers

0
Julio Chamizo On

I've found the answer, and it's simpler than I thought, and it's possible to do it by simply adding an array to the main query.


    *[_type == 'cases' && caseSlug.current == "amazon-prime-india"]
        {...,
       caseBrand -> {
         brandName,
        brandImage
        },
       caseAgency -> {
         agencyName,
        agencyLogo
        }
    
    }

My schema "Cases" already have references to Brand and Agency. So basically, what I need to do is the following:

  1. Get all the info from the Specific Case (this is the main Query)
  2. Add an Array with referenced type