schickling
schickling

Reputation: 4240

Realm: Update/Set relationship without updating existing child object

Given the following data model, is there a way to update or set a child relationship without updating the (existing) child object?

Data Model

class Person: Object {
    dynamic var id = 0
    dynamic var dog: Dog?

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

class Dog: Object {
    dynamic var id = 0
    dynamic var name = ""

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

Code

let realm = Realm()

// query existing dog
let existingDog = realm.objectForPrimaryKey(Dog.self, key: 42)
print(existingDog) // id: 42, name: Rex

// create new dog and person
let newDog = Dog(value: ["id": 42, "name": "Pluto"])
let person = Person()


realm.write {
    // this shouldn't update the existing dog
    // i.e. the name of the dog with id: 42 in the database should still be "Rex"
    person.dog = newDog
    realm.add(person, update: true)
}

I've also tried to do this via realm.create but had no success either. Any ideas?

Upvotes: 3

Views: 1528

Answers (1)

ezcoding
ezcoding

Reputation: 2996

The id property in your Dog class is a primaryKey. Primary keys have the purpose to mark an entry in a Database as unique. So if you create an Object using the same primary key, you will override any existing data in the Database, which has the primary key.

I don't understand, what you exactly want to achieve, but there should be no reason for your Dog Table to have multiple Objects with the same primary key. That's not how Relational Databases are meant to work.

If you need however to have a Dog named Pluto and a Dog named Rex with the same id value, then should probably create a new attribute which is not unique (-> not marked as primary key).

Upvotes: 4

Related Questions