Search code examples
react-nativerealm

Implementing insertion of simple relationship model (nested objects)


I'm trying to shift my mind from rational database to realm and I have a small issue.

I have 2 data models :

Station.schema = {

name: 'Station',
primaryKey: 'id',
properties:{
    id:    'int',    // primary key
    stationName : {type: 'string'},
    stationType : {type:'StationType'}       
} 

}

StationType.schema = {

name: 'StationType',
primaryKey: 'id',
properties:{
    id:    'int',    // primary key
    typeName : {type: 'string'},
} 

}

Im trying to insert new record of object "station" which has an object property named "stationType" . the stationType object is pre populated with fixed values.

Whenever im executing the insert of object "Station" it tries to insert the value for the "stationType" property which already exists.

How can I prevent the insertion of the object property ? I only want the "stationType" property to point to a a record in the "StationType" model.

Thank you

Yuval


Solution

  • How can I prevent the insertion of the object property ?

    You don't need to prevent it, because if you specify true parameter for realm.create(), then if it exists, it'll try to update it instead of creating it.

    realm.write(() => {
      // Create a book object
      realm.create('Book', {id: 1, title: 'Recipes', price: 35});
    
      // Update book with new price keyed off the id
      realm.create('Book', {id: 1, price: 55}, true); // <-- true
    });
    

    If you don't want to update it, then you need to query for the managed object, and modify the managed object inside the transaction as you like.

    EDIT:

    If your managed object is already created by realm.create(), then you can query it like so

    realm.write(() => {
        let book = realm.objects('Book').filtered('bookId == ' + bookId)[0];
        if(book == null) {
            book = realm.create('Book', {id: 1, title: 'Recipes');
        }
        let author = realm.objects('Author').filtered('authorId == ' + authorId)[0];
        book.author = author; // sets the field for the managed object
    }