Reputation: 1907
I have the following Realm Object structure:
class ParentObject: Object {
let nestedObjects = List<NestedObject>
}
class NestedObject: Object {
@objc dynamic var id: Int = 0
}
Is it possible to filter ParentObject
s to return only those that contain NestedObject
s whose id
matches one of those contained in an array?
I tried doing it this way:
let ids = [1, 2, 3]
let filtered = realm
.objects(ParentObject.self)
.filter("nestedObjects.id IN %@", ids)
But I'm getting this error: Terminating app due to uncaught exception 'Invalid predicate', reason: 'Key paths that include an array property must use aggregate operations'
.
Maybe I should try doing it with multiple OR
s instead of IN
?
Upvotes: 2
Views: 2388
Reputation: 915
new realm safe query syntax (10.19 I think) : example looking for all parents with a nested object with id = myID and with a type = myType
let filtered = realm
.objects(ParentObject.self)
.where ({ parent in
parent.nestedObjects.id == myId &&
parent.nestedObjects.type == myType
})
with old predicate syntax :
let filtered = realm
.objects(ParentObject.self)
.filter("ANY nestedObjects.id IN %@", [myId])
.filter("ANY nestedObjects.type IN %@)", [myType])
Upvotes: 0
Reputation: 18308
You want a predicate of ANY nestedObjects.id IN %@
. The ANY
/ALL
/NONE
modifier is important as it determines how many of the objects in the collection must match for the predicate to evaluate to true.
Upvotes: 7