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.
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 }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With