2017-10-19 81 views
0

我试图将我的思想从理性数据库转移到领域,我有一个小问题。实现插入简单的关系模型(嵌套对象)

我有2个数据模型:

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'}, 
} 

}

我试图插入对象“station”的新记录,该记录具有名为“stationType”的对象属性。 stationType对象预填充了固定值。

每当我执行插入的对象“站”时,它会尝试插入已存在的“stationType”属性的值。

如何防止插入对象属性?我只希望“stationType”属性指向“StationType”模型中的记录。

谢谢

尤瓦

回答

0

如何防止对象属性的插入?

你并不需要,以防止它,因为如果你指定true参数为realm.create(),那么如果它存在,它会尝试,而不是更新它创建它的。

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 
}); 

如果您不想更新它,那么您需要查询托管对象,并根据需要修改事务内的托管对象。

编辑:

如果你的管理对象已经被realm.create()创建的,那么你就可以查询它像这样

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 
} 
+0

感谢。 我意识到'真实'的论点,但它不觉得这是我应该用在这种情况下。 你能解释更多关于第二种选择吗?你是否提到类型更新? – Yuval

+0

希望我的编辑帮助。 – EpicPandaForce

+0

清除,谢谢! – Yuval