我想查询所有带有多个过滤器的产品,例如:
所有产品:[(name: "cookies", brand: "brand x"), (name: "water", brand: "brand y")]
如果我只有一个过滤器,例如(name: "cookies", brand: "brand x")
答案很明确:name == \(tuple.name) AND brand == \(tuple.brand)
如果我有多个元组但只有一个属性,那么它也很清楚:
return "name IN {\(["cookies", "water"].joined(separator: ","))}"
但是如何为我的元组数组编写过滤器?一个想法是使用前一个查询Results
将每个作为单个name == \(tuple.name) AND brand == \(tuple.brand)
获取,并使用此构建一个数组,但我需要Results
中的最终结果而不是数组。
也可能这样,但我认为这是不可能的?
return "name::brand IN {\(["cookies::brand x", "water::brand y"].joined(separator: ","))}"
答案 0 :(得分:6)
似乎您希望将谓词与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)