From 704e6f2f6d6a0fddd02eca4037a94328725995a7 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 6 Sep 2022 21:37:31 -0700 Subject: [PATCH] Add Include Attributes When Conditional Check Passes as a GROQ TIL --- README.md | 3 +- ...ttributes-when-conditional-check-passes.md | 40 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 groq/include-attributes-when-conditional-check-passes.md diff --git a/README.md b/README.md index e027380..11db12b 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/groq/include-attributes-when-conditional-check-passes.md b/groq/include-attributes-when-conditional-check-passes.md new file mode 100644 index 0000000..76a68e0 --- /dev/null +++ b/groq/include-attributes-when-conditional-check-passes.md @@ -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)