Search code examples
iosswiftrealmnspredicate

filter list on inverse relationship


I struggle a bit today, taking the example given on RealmSwift documentation, what I am trying to do is find the query that will allow me to get the dogs (from the dog object) who only have at least one owner.

class Person: Object {
    // ... other property declarations
    let dogs = List<Dog>()
}

class Dog: Object {
    dynamic var name = ""
    dynamic var age = 0
    let owners = LinkingObjects(fromType: Person.self, property: "dogs")
}

I have this basic method :

public class func getDogs() -> Results<Dog>? {
    do {
        let aRealm = try Realm()
        let dogs = aRealm.objects(Dog.self).filter("ANY owners != nil")
        return dogs
    } catch {
        print(error)
    }
    return nil
}

but it fails so I assume my query is incorrect, though I failed to find any documentation on this, any insight would be much appreciated.


Solution

  • You can use the aggregate expression, @count. The following query filters dogs that have at lease more than one owner.

    let dogs = aRealm.objects(Dog.self).filter("owners.@count > 0")
    

    Please see more details: https://realm.io/docs/swift/latest/#filtering