2

根据v0.102.0 的 Realm 文档,这是创建反向关系的方式:

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,并且我们想要创建一个反向关系,称为buyersthat 跟踪哪些实例Person具有Dog吃 的实例DogFood。我们可以尝试以下方法:

狗 (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")
}

但是,这会引发以下错误:Property 'dogs.favoriteFoods' declared as origin of linking objects property 'buyers' does not exist.

有没有其他方法可以达到同样的效果?

4

1 回答 1

2

这可以通过过滤器来实现,但需要注意的是,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")
        }
    }
}

该属性realm是类型的Realm?,并且通过从 继承而来Object。它指向特定Object实例所在的领域,nil如果没有分配给一个,则返回。如果是这种情况,我们强制该属性items返回一个空集Results<Person>

于 2016-05-12T20:15:49.787 回答