Many-to-one with primary key (unique constraint)

I've got an Article and a Category model linked by a many-to-one relationship. However, the Category model has a unique constraint on the id property because it's the primary key as you can see below.

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"
    }
}

This will work until an Article got the same Category and throw an exception because of the unique constraint.

How am I supposed to implement this kind of relationship ? Is there any built-in way to persist only the Category id and retrieve the corresponding Category ?

Thanks

Upvotes: 0

Views: 673

Answers (1)

jregnauld
jregnauld

Reputation: 1298

As you can read in Realm doc (0.92.1), you have to use a List<Object> for a many-to-one relationship.

See this link :

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)

So in your case, I guess it should be something like that :

   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"
    }
}

If your Realm version is older :

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

    }

Upvotes: 1

Related Questions