1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00

Add Include Attributes When Conditional Check Passes as a GROQ TIL

This commit is contained in:
jbranchaud
2022-09-06 21:37:31 -07:00
parent 35e0567556
commit 704e6f2f6d
2 changed files with 42 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1239 TILs and counting..._
_1240 TILs and counting..._
---
@@ -344,6 +344,7 @@ _1239 TILs and counting..._
- [Grab Multiple Values From A Reference](groq/grab-multiple-values-from-a-reference.md)
- [Grab Values From An Array Of References](groq/grab-values-from-an-array-of-references.md)
- [Include Attributes When Conditional Check Passes](groq/include-attributes-when-conditional-check-passes.md)
- [Include Type Of Operation In Webhook Response](groq/include-type-of-operation-in-webhook-response.md)
### Heroku

View File

@@ -0,0 +1,40 @@
# Include Attributes When Conditional Check Passes
The graph-like nature of Sanity means that you'll often be querying for data
that spans a variety of document types. For instance, your front-end could be
requesting content in the shape of a blog post, video, and podcast. Though
there are some similarities, each of these document types will have some unique
attributes.
When using GROQ to query for data that spans different types of documents, you
can use [a conditional query
syntax](https://www.sanity.io/docs/query-cheat-sheet#64a36d80be73) to include
type-specific attributes.
```groq
*[_type == 'blog' || _type == 'video' || _type == 'podcast'][]{
title,
'slug': slug.current,
_type == 'blog' => {
body,
read_time
},
_type == 'video' => {
description,
mp4_url
},
_type == 'podcast' => {
description,
mp3_url
}
}
```
Notice that there are some attributes that are common across each type (i.e.
`title` and `slug`). Each type then has attributes unique to its document type
(i.e. `blog` has `body` and `read_time`).
This conditional query syntax allows us to both define flexible schemas in
Sanity and then query against that flexible schema.
[source](https://www.youtube.com/watch?v=dCGPNkcTseQ)