Realm中是否有可能获得一对一关系的反比关系?
例如:
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
还有:
let arbitraryPerson = realm.objects(Person).filter("name contains 'Harry'").first!
let dogOwned = arbitraryPerson.dog
print(dogOwned?.name) // -> result is nil
似乎ownDog始终为nil
。为什么不能确定反比关系?或dog
是否应始终为list<T>
类型(即多对多关系)以强制这些对象之间的关系?在这种情况下,我得到它的工作,但是当它不是很多时,强迫一个多对多的关系感觉不正确。
答案 0 :(得分:5)
LinkingObjects
对象必须是模型对象的一个属性,以便Realm知道它所使用的对象:
class Person: Object {
dynamic var name: String?
let _dogs = LinkingObjects(fromType: Dog.self, property: "owner")
var dog: Dog? { return _dogs.first }
}
答案 1 :(得分:1)
据我所知,Realm中的关系默认情况下不是双向的,因为您可能习惯使用Core Data。因此,如果您希望两个对象都知道关系,则必须同时设置它;
dog.owner = person
person.ownedDog = dog