Chained projections

So far you have only written a single projection after a each filter. It is possible to chain projections, where each projection only contains the attributes of the previous one.
headline
and venue
to return a title
string for the event*[ _type == "event" && defined(headline) && defined(venue)][0]{ headline->{name}, venue->{name}}{ "title": headline.name + " at " + venue.name}
You might think about this as using each projection to create a variable which can be used in the next projection.
In the example above we know headline
and venue
are defined because that has been added to the filter.
But the same query can be even more flexible and handle instances where data could be missing.
title
string using select()
*[_type == "event"][0]{ headline->{name}, venue->{name}}{ "title": select( headline.name && venue.name => headline.name + " at " + venue.name, headline.name => headline.name, venue.name => venue.name, "Untitled event" )}
The select()
GROQ function will return the first item that returns true. In this instance, any event that has both a headline
and venue
will return the complete string. Otherwise fall back to either the headline
name, or venue
name, or a string "Untitled event."
When you need to use dynamic values in GROQ queries you turn to parameters, let's look at those in the next lesson.