Can you write a conditional GROQ request based on document fields in Sanity.io?
"models": select(
type == "brand" => select(
filterVehicleGroup != null => *[_type == "model" && brand._ref == ^.brand._ref && vehicleGroup == ^.filterVehicleGroup] | order(_createdAt desc) {
"_key": _id,
${MODEL_CONTENT}
},
*[_type == "model" && brand._ref == ^.brand._ref] | order(_createdAt desc) {
"_key": _id,
${MODEL_CONTENT}
},
),
type == "selected" => selected[]-> {
_key,
${MODEL_CONTENT}
}
)filterVehicleGroupis the filter. The idea is to add multiple filters in the same way, where it adds it to the query if it's set or not equal to "all", like this for each filter:
filterFieldNameInDoc == filterValue*[_type == "model"
&& ($filter1 == null || filter1 == $filter1)
&& ($filter2 == null || filter2 == $filter2)
&& ($filter3 == null || filter3 == $filter3)
&& ($filter4 == null || filter4 == $filter4)
&& ($filter5 == null || filter5 == $filter5)
]Was this answer helpful?
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.