🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

How to unify embedded content and references from the same array in a GROQ query.

2 replies
Last updated: Apr 20, 2021
GROQ Query to unify embedded content and references from same array? 
Hi All,
 
I'm trying to model an "Icon List" in my front end, using a page-builder approach (See attached picture for end result). I have modelled 2 document types:
• "iconText" - captures a short piece of text with an icon and heading (see attached screenshot)
• "iconTextList" - which assembles a list of iconTexts for display on the frontend.
 
So far so good… But what I want to achieve is for the iconText to EITHER be referenced from pre-existing iconText documents, OR allow the user to input an embedded iconText inside the iconTextList. I have modelled this using a simple array which allows both References to iconText and iconText embedded directly as an object (see schema below).
 
Now I would like my front end not to care if the iconTexts in the list are referenced documents or embedded, and just receive a list of iconTexts. 
Can anyone help me with a GROQ query to unify the output so all the references are followed and delivered in order alongside my embedded.
Hope this is all clear! Thanks in Advance

iconText Schema:

export default {
  name: "iconText",
  title: "Icon Text",
  type: "document",
  fields: [
    {
      name: "icon",
      type: "icon", //this is actually just a string with predefined options
      title: "Icon",
    },
    {
      name: "header",
      type: "array",
      title: "Header",
      of: [
        {
          type: "block", //...
    {
      name: "detail",
      type: "array",
      title: "Detail",
      of: [{ type: "block" }], //...
    },
  ]
}
iconTextList Schema:

export default {
  name: "iconTextList",
  title: "Icon Text List",
  type: "document",
  fields: [
    {
      name: "content",
      type: "array",
      title: "Icon",
      of: [
        {
          title:
            "Add your own Icon Text",
          type: "iconText",
        },
        {
          title:
            "Select existing Icon Text",
          type: "reference",
          to: [{ type: "iconText" }],
        },
      ],
    },
  ],
};
Desiered output is comthing like:

[{
]
Apr 20, 2021, 2:54 PM
Try to query both first and join the results afterwards:
{
  'a': *[ icon_text_list_matches ],
  'b': *[ icon_text_matches ],
} | {
  'joined': [...a, ...b]
}.joined
Apr 20, 2021, 3:15 PM
Thanks Geoff. Works like a charm. I am blown away by the elegance of that. 🙌
Apr 20, 2021, 4:26 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?