Reputation: 9018
How can I filter objects using more than one property on the child objects. So "find all parents with male children older than 10"
class Parent: Object {
@objc dynamic var name: String?
let children = List<Child>()
}
class Child: Object {
@objc dynamic var name: String?
@objc dynamic var gender: String?
@objc dynamic var age: Int?
}
let filtered = realm.objects(Parent.self).filter("ANY (children.name == %@ && children.gender == %@)", "some name", "male")
It doesn't seem like this is a valid query.
Or do I have to do something like this which strangely also seems to give the incorrect result - but I might need to do some more testing on this.
let filtered = realm.objects(Parent.self).filter("ANY children.name == %@", "some name").filter("ANY children.gender == %@", "male")
In the end it seems that first getting all children that match the criteria and then finding the parents of those children worked reliably.
let matchingChildren = realm.objects(Child.self).filter("name == %@ && gender == %@)", "some name", "male")
let parentsOfMatchingChildren = realm.objects(Parent.self).filter("ANY children IN %@", matchingChildren)
Upvotes: 0
Views: 368
Reputation: 275085
I don't think you can use ANY
with a complicated expression in parenthesis like that. You need split the ANY
:
ANY children.name == %@ && ANY children.age > %@
Also, %@
is for objects (such as strings). For an integer like age, you need to use %d
:
ANY children.name == %@ && ANY children.age > %d
Alternatively, you can use SUBQUERY
as well:
SUBQUERY(children, $child, $child.name == %@).@count > 0 && SUBQUERY(children, $child, $child.age >%d).@count > 0
Upvotes: 1