Querying references inside a Portable text field in Sanity
8 replies
Last updated: Jan 11, 2022
C
Following the field level translation documentation, I have a content object that contains the languages as keys. Normally I can access any field like this.
This content is a Portable text field, and I want to query the current language or fallback, but I want to be able to reach the references inside that object, like referenced images.
Say I want to access this asset of
This doesn’t work:
How would you query that?
"content": coalesce(content[$lang], content.en)
This content is a Portable text field, and I want to query the current language or fallback, but I want to be able to reach the references inside that object, like referenced images.
Say I want to access this asset of
pageImagethat is a block inside `content`:
_type == "pageImage" => {
...,
"alt": coalesce(alt[$lang], alt.en),
"imageBlock": imageBlock {
"asset": asset->url,
"dimensions": asset->metadata.dimensions
},
},
This doesn’t work:
"content": coalesce(content[$lang], content.en) {
....,
_type == "pageImage" => {
...,
alt,
"imageBlock": imageBlock {
"asset": asset->url,
"dimensions": asset->metadata.dimensions
},
},
}
How would you query that?
Jan 11, 2022, 4:31 PM
A
Hi! Using
coalesce()in this way should work fine. Which API version are you on?
Jan 11, 2022, 4:55 PM
C
The api version is “2021-03-25”
If I only query this
I get null. Should I change the api version to something else?
If I only query this
"content": coalesce(content[$lang], content.en) {
...,
}
I get null. Should I change the api version to something else?
Jan 11, 2022, 5:21 PM
A
Odd. That API version should work.
Jan 11, 2022, 5:31 PM
A
Can you do just:
and see?
Also, if that returns null, how about just:
"content": coalesce(content[$lang], content.en)
Also, if that returns null, how about just:
"content": coalesce(content[$lang])
Jan 11, 2022, 5:32 PM
C
"content": coalesce(content[$lang], content.en)
Jan 11, 2022, 6:01 PM
C
In the output of content I will get
How do I access that reference?
"imageBlock": { "_type": "image", "asset": { "_ref": "image-e54e00da4b0c81d18aea3260fd7a551b5f914121-702x490-gif", "_type": "reference" }
Jan 11, 2022, 6:01 PM
C
I found the solution! After coalesce() I should query inside the array, not an object key.
"content": coalesce(content[$lang], content.en)[] {
...,
_type == "image" => {
...,
alt,
"imageBlock": imageBlock {
"asset": asset->url,
"dimensions": asset->metadata.dimensions
},
}
}
Jan 11, 2022, 6:08 PM
A
Ah, for some reason I thought
content[...]was an object. 🙂 Great!
Jan 11, 2022, 6:13 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.