According to the Realm documentation for v0.102.0, this is how you create an inverse relationship:
Person
class Person: Object {
// ... other property declarations
let dogs = List<Dog>()
}
Dog (v1)
class Dog: Object {
// ... other property declarations
let owners = LinkingObjects(fromType: Person.self, property: "dogs")
}
Suppose that we have another class, called DogFood, and we want to create an inverse relationship called buyers that tracks which instances of Person have a Dog that eats that instance of DogFood. We could try the following:
Dog (v2)
class Dog: Object {
// ... other property declarations
let favoriteFoods = List<DogFood>
let owners = LinkingObjects(fromType: Person.self, property: "dogs")
}
DogFood
class DogFood: Object {
// ... other property declarations
let buyers = LinkingObjects(fromType: Person.self, property: "dogs.favoriteFoods")
}
However, this throws the following error: Property 'dogs.favoriteFoods' declared as origin of linking objects property 'buyers' does not exist.
Is there another way to achieve the same effect?
This can be achieved with a filter, with the caveat that the
DogFoodobject we need to query about needs to be part of aRealm.The code would go as follows:
The property
realmis of typeRealm?and comes into the picture through inheritance fromObject. It points towards the realm that a particularObjectinstance is in and returnsnilif not assigned to one. If that is the case, we force the propertyitemsto return an empty set ofResults<Person>.