Reputation: 32269
I want to query all the products with multiple filters, e.g.:
All products with: [(name: "cookies", brand: "brand x"), (name: "water", brand: "brand y")]
If I had only one filter, e.g. (name: "cookies", brand: "brand x")
the answer would be clear: name == \(tuple.name) AND brand == \(tuple.brand)
If I have multiple tuples but with only one property, it wold also be clear:
return "name IN {\(["cookies", "water"].joined(separator: ","))}"
But how do I write the filter for my array of tuples? An idea would be to fetch each as single Results
using the former query name == \(tuple.name) AND brand == \(tuple.brand)
, and build an array with this, but I need the end result in Results
not an array.
Also something like this maybe but I think this is not possible?
return "name::brand IN {\(["cookies::brand x", "water::brand y"].joined(separator: ","))}"
Upvotes: 2
Views: 895
Reputation: 14409
Seems like you want to combine predicates together with NSCompoundPredicate
:
class Product: Object {
dynamic var name = ""
dynamic var brand = ""
}
let productsFilter: [(name: String, brand: String)] = [("cookies", "brand x"), ("water", "brand y")]
let subPredicates = productsFilter.map {
NSPredicate(format: "name = %@ && brand = %@", $0.name, $0.brand)
}
let compoundPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: subPredicates)
let realm = try Realm()
let products = realm.objects(Product.self).filter(compoundPredicate)
Upvotes: 6