简体   繁体   中英

How to Add a Conditional whereField to a Firestore Query

I'm querying Firestore collections using .whereField . Depending on the user input, it may be a single-condition or multiple-condition query. Eg,

myCollection
.whereField("color", isEqualTo: selectedColorArgument)
.whereField("shape", isEqualTo: selectedShapeArgument)

How can I code this query so that a condition is only queried for when a value is selected? Eg, if no "shape" is selected, then there should not be a .whereField("shape", isEqualTo: selectedShapeArgument) condition considered in the query. I was considering a switch statement but there would too many cases with more possible conditions to select.

Firestore queries follow a builder pattern, where each call to whereField returns a new Query object.

So you can initialize a query variable like this:

Query query = myCollection;

And then conditionally replace the variable for each condition:

if condition {
  query = query.whereField("color", isEqualTo: selectedColorArgument)
}
if condition2 {
  query = query.whereField("shape", isEqualTo: selectedShapeArgument)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM