具有主键的多对一(唯一约束)

时间:2015-05-07 18:39:53

标签: ios swift realm

我有一个由多对一关系链接的文章和类别模型。但是,Category模型对id属性有唯一约束,因为它是主键,如下所示。

class Article: Object
{
    dynamic var id: String = ""
    dynamic var title: String = ""
    dynamic var category: Category()

    override static func primaryKey() -> String? {
        return "id"
    }
}

class Category: Object
{
    dynamic var id: String = ""
    dynamic var title: String = ""

    override static func primaryKey() -> String? {
        return "id"
    }
}

这将一直有效,直到一篇文章获得相同的类别并因为唯一约束而抛出异常。

我该如何实施这种关系?是否有任何内置方法仅保留Category id并检索相应的Category?

由于

1 个答案:

答案 0 :(得分:1)

正如您可以在Realm doc(0.92.1)中阅读的那样,您必须使用List<Object>来实现多对一关系。

请看这个链接:

http://realm.io/docs/swift/latest/

class Dog: Object {
    dynamic var name = ""
    dynamic var owner: Person? // Can be optional
}
    class Person: Object {
        ... // other property declarations
        let dogs = List<Dog>()
    }

    let someDogs = Realm().objects(Dog).filter("name contains 'Fido'")
    jim.dogs.extend(someDogs)
    jim.dogs.append(rex)

所以在你的情况下,我想它应该是这样的:

   class Article: Object
{
    dynamic var id: String = ""
    dynamic var title: String = ""
    override static func primaryKey() -> String? {
        return "id"
    }
}
class Category: Object
{
    dynamic var id: String = ""
    dynamic var title: String = ""
    dynamic var articles = List<Article>()
    override static func primaryKey() -> String? {
        return "id"
    }
}

如果您的Realm版本较旧:

 class Category: Object
    {
       ...
        dynamic var categories = RLMArray(objectClassName: Article.className())

    }