简体   繁体   中英

Realm Swift - filter objects using List properties (more than one)

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM