【问题标题】:Filter realm results with ANY and AND使用 ANY 和 AND 过滤领域结果
【发布时间】:2025-12-13 21:05:01
【问题描述】:

我有这个 NSPredicate:

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

以上代码返回所有具有属性'prop1'的子级或键'key1'的子级的对象

我需要的是只返回具有属性“prop1”和键“key1”的孩子的对象

详细说明

我有Persons 的对象

每个Person 都有一个childs 属性,它是Kid 的列表

每个Kid 都有两个字符串属性propkey

  • Person[0] 在孩子列表中有两个孩子

    • Kid[0].prop = prop1Kid[0].key = key1

    • Kid[1].prop = prop2Kid[0].key = key2

  • Person[1] 在孩子列表中有两个孩子

    • Kid[0].prop = prop1Kid[1].key = key2
    • Kid[1].prop = prop2Kid[1].key = key1

上面的谓词返回两个人,而我需要的是只返回第一个人,因为只有第一个人有prop1key1 的孩子

非常感谢您的帮助

【问题讨论】:

    标签: swift realm nspredicate


    【解决方案1】:

    为了确保两个条件都由同一个对象满足,您需要使用子查询:

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

    【讨论】: