Skip to content

Commit 2978c94

Browse files
committed
Add Grab Multiple Values From A Reference as a GROQ TIL
1 parent 1ac43cc commit 2978c94

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1230 TILs and counting..._
13+
_1231 TILs and counting..._
1414

1515
---
1616

@@ -342,6 +342,7 @@ _1230 TILs and counting..._
342342

343343
### GROQ
344344

345+
- [Grab Multiple Values From A Reference](groq/grab-multiple-values-from-a-reference.md)
345346
- [Grab Values From An Array Of References](groq/grab-values-from-an-array-of-references.md)
346347
- [Include Type Of Operation In Webhook Response](groq/include-type-of-operation-in-webhook-response.md)
347348

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Grab Multiple Values From A Reference
2+
3+
Let's say we have an `author` with some attributes including a reference to a
4+
`person` which contains more data about the person. Here is one way to write a
5+
query to access that data.
6+
7+
```groq
8+
*[_type == 'author' && slug.current == 'donna-tartt']{
9+
website,
10+
'firstName': person->firstName,
11+
'lastName': person->lastName,
12+
'age': person->age
13+
}
14+
```
15+
16+
Here is another way to write this query that doesn't do three separate accesses
17+
on the `person` reference.
18+
19+
```groq
20+
*[_type == 'author' && slug.current == 'donna-tartt']{
21+
website,
22+
person-> {
23+
'firstName': firstName,
24+
'lastName': lastName,
25+
'age': age
26+
}
27+
}
28+
```
29+
30+
This isn't quite right though because it leaves the three reference values
31+
nested under `person`. We can get back to the original shape of our query by
32+
flattening the `person` object using familiar looking spread syntax (`...`).
33+
34+
```groq
35+
*[_type == 'author' && slug.current == 'donna-tartt']{
36+
website,
37+
...person-> {
38+
'firstName': firstName,
39+
'lastName': lastName,
40+
'age': age
41+
}
42+
}
43+
```

0 commit comments

Comments
 (0)