根据Realm documentation for v0.102.0 ,这就是创建逆关系的方法:
人
class Person: Object {
// ... other property declarations
let dogs = List<Dog>()
}
狗(v1)
class Dog: Object {
// ... other property declarations
let owners = LinkingObjects(fromType: Person.self, property: "dogs")
}
假设我们有另一个类,名为 DogFood
,并且我们想要创建一个名为 buyers
的逆关系,用于跟踪 Person
的实例有一只吃 DogFood
实例的 Dog
。我们可以尝试以下方法:
狗(v2)
class Dog: Object {
// ... other property declarations
let favoriteFoods = List<DogFood>
let owners = LinkingObjects(fromType: Person.self, property: "dogs")
}
狗粮
class DogFood: Object {
// ... other property declarations
let buyers = LinkingObjects(fromType: Person.self, property: "dogs.favoriteFoods")
}
但是,这会引发以下错误:声明为链接对象属性“buyers”来源的属性“dogs.favoriteFoods”不存在。
还有其他方法可以达到同样的效果吗?
最佳答案
这可以通过过滤器来实现,但需要注意的是 DogFood
我们需要查询的对象需要是 Realm
的一部分.
代码如下:
class DogFood: Object {
// ... other property declarations
var items: Results<Person> {
if let realm = self.realm {
return realm.objects(Person).filter(NSPredicate(format: "ANY dogs.favoriteFoods.id == %@", self.id))
} else {
return RealmSwift.List<Person>().filter("1 != 1")
}
}
}
该属性(property)realm
类型为Realm?
并通过继承 Object
进入图片。它指向特定的 Realm Object
实例已存在并返回 nil
如果没有分配给一个。如果是这种情况,我们强制使用属性 items
返回空集 Results<Person>
.
关于swift - 使用多级属性在 RealmSwift 中创建 LinkingObjects 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37168662/