Is there any elegant way to dynamically add where condition to the query based on conditions? For e.g, the default query is
query = collectionReference
.whereField(SaleProperties.saledate.rawValue, isGreaterThanOrEqualTo: startDate)
.whereField(SaleProperties.saledate.rawValue, isLessThanOrEqualTo: endDate)
.whereField(SaleProperties.isapprovedbystoremanager.rawValue, isEqualTo: true)
and I have 4 different conditions, like, state, division, store, user
. When these filters is/are selected, I need to add where condition accordingly. Lets assume, I have selected state
then the query would be
query = collectionReference
.whereField(SaleProperties.state.rawValue, isEqualTo: selectedState)
.whereField(SaleProperties.saledate.rawValue, isGreaterThanOrEqualTo: startDate)
.whereField(SaleProperties.saledate.rawValue, isLessThanOrEqualTo: endDate)
.whereField(SaleProperties.isapprovedbystoremanager.rawValue, isEqualTo: true)
likewise, if I have selected state and division
query = collectionReference
.whereField(SaleProperties.state.rawValue, isEqualTo: selectedState)
.whereField(SaleProperties.division.rawValue, isEqualTo: selectedDivision)
.whereField(SaleProperties.saledate.rawValue, isGreaterThanOrEqualTo: startDate)
.whereField(SaleProperties.saledate.rawValue, isLessThanOrEqualTo: endDate)
.whereField(SaleProperties.isapprovedbystoremanager.rawValue, isEqualTo: true)
Above example is illustrated just for two conditions. Like this, I need to check for 4 different conditions with combination of others.The probability of combination will be like 24 queries. So It would be great if someone knows the elegant way to form the queries.
*********Answer********
With the default query (please see above the default query), I check for the condition, example, if state
is selected, then I just add one more condition to the default query
if(isStateSelected == true)
{
query = query.whereField(SaleProperties.state.rawValue, isEqualTo: selectedState)
}
likewise, if division
is selected
if(isDivisionSelected == true)
{
query = query.whereField(SaleProperties.division.rawValue, isEqualTo: selectedDivision)
}
so if conditions are true, additional condition will be added to the default query