2017-10-19 79 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