Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine an inverse relationship of a to-one relationship using Realm?

Tags:

ios

swift

realm

Is it possible in Realm to obtain the inverse relation of a to-one relationship?

For example:

    class Dog: Object {
        dynamic var name: String?
        dynamic var owner: Person?
    }

    class Person: Object {
        dynamic var name: String?
        let dog = LinkingObjects(fromType: Dog.self, property: "owner").first
    }



    let person = Person()
    person.name = "Harry"
    try! realm.write {
        realm.add(person)
    }


    let dog = Dog()
    dog.name = "Fido"
    dog.owner = person
    try! realm.write {
        realm.add(dog)
    }


    print(person.dog?.name) // -> result is nil

And also:

    let arbitraryPerson = realm.objects(Person).filter("name contains 'Harry'").first!
    let dogOwned = arbitraryPerson.dog

    print(dogOwned?.name) // -> result is nil

It seems that ownedDog is always nil. Why could the inverse relation not be determined? Or should dog always be of list<T> type (i.e. to-many relationship) to force a relation between these objects? In this situation I get it working, but it feels not correct to force a to-many relationship when it isn't.

like image 685
Gerard Avatar asked Dec 08 '25 14:12

Gerard


1 Answers

The LinkingObjects object has to be a property of your model object for Realm to know what object it goes with:

class Person: Object {
    dynamic var name: String?
    let _dogs = LinkingObjects(fromType: Dog.self, property: "owner")
    var dog: Dog? { return _dogs.first }
}
like image 51
Thomas Goyne Avatar answered Dec 10 '25 05:12

Thomas Goyne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!