Search code examples
swiftrealmnspredicate

Filter realm results with ANY and AND


I have this NSPredicate:

results?.filter("ANY childs.property = 'prop1' AND ANY childs.key contains[c] %@", "key1")

The above code returns all objects that have a child of property 'prop1' or a child of key 'key1'

What I need is to return only the objects that have a child with both property 'prop1' AND key 'key1'

Detailed Explanation

I have objects of Persons

Each Person has a childs property which is a list of Kid

Each Kid has two string properties prop and key

  • Person[0] has two Kids in the childs list

    • Kid[0].prop = prop1 and Kid[0].key = key1

    • Kid[1].prop = prop2 and Kid[0].key = key2

  • Person[1] has two Kids in the childs list

    • Kid[0].prop = prop1 and Kid[1].key = key2
    • Kid[1].prop = prop2 and Kid[1].key = key1

The predicate above returns both Persons, while what I need for it is to return only the first person because only the first person has a child with prop1 and key1

Help is much appreciated


Solution

  • To the ensure that both of the criteria are fulfilled by the same object, you need to use a subquery:

    results?.filter("SUBQUERY(childs, $child, $child.property = 'prop1' AND $child.key contains[c] %@).@count > 0", "key1")