2016-11-23 77 views
1

我有2個領域數據模型。 「食物」模型具有對象屬性類型'foodRating',旨在成爲FoodRatings模型的鏈接。Realm React Native - 如何分配對象屬性類型

class FoodRatings extends Realm.Object {} 
FoodRatings.schema = { 
    name: 'FoodRatings', 
    primaryKey: 'foodRatingId', 
    properties: { 
    foodRatingId: { type: 'int', indexed: true }, 
    name: 'string', 
    } 
}; 


class Foods extends Realm.Object {} 
Foods.schema = { 
    name: 'Foods', 
    primaryKey: 'foodId', 
    properties: { 
    foodId: { type: 'int', indexed: true }, 
    name: 'string', 
    foodRating: {type: 'FoodRatings'}, 
    } 
}; 

FoodRatings預先填充了許多旨在靜態且不變的行。您從FoodRatings的某個選項中爲食物分配foodRating。

我遇到的問題是當我嘗試創建一個新的食物對象併爲FoodRatings對象分配一個FoodRatings對象時,它會中斷。

foodRatings = realm.objects('FoodRatings') 
let foodRating = foodRatings.filtered('foodRatingId = 1'); 
realm.write(() => { 
    realm.create('Foods', {foodId: 1, name: 'apples', foodRating: foodRating[0]}); 
}) 

我看到很多關於領域的「連接」的討論,但它尚未發佈到領域js。所有示例和文檔假設新條目而不是您要分配給模型的現有對象。

任何想法我可以做到這一點?

回答

1

免責聲明首先 - 我使用Realm Swift並從未使用Realm React Native。

話雖如此,從文檔看來,它看起來像你有錯誤的定義foodRating。我本來應該像這樣的例子

cars: {type: 'list', objectType: 'Car'} 

即,

foodRating: {type: 'list', objectType: 'FoodRatings'} 

「鏈接」存在的境界斯威夫特,但在你的情況下,可能會被用於從食品評級鏈接到所有有評級的食物。所以我認爲它解決了一個不同的問題。

1

你看到了什麼錯誤?

你的榜樣爲我工作

realm.write(() => { 
    realm.create('FoodRatings', {foodRatingId: 10, name: '1 star'}); 
    realm.create('FoodRatings', {foodRatingId: 20, name: '2 star'}); 
    realm.create('FoodRatings', {foodRatingId: 30, name: '3 star'}); 
}); 

let foodRatings = realm.objects('FoodRatings'); 
foodRating = foodRatings.filtered('foodRatingId = 10'); 
realm.write(() => { 
    realm.create('Foods', {foodId: 1, name: 'apples', foodRating: foodRating[0]}); 
}); 

let foods = realm.objects('Foods'); 
console.log("foods[0]= " + foods[0].name);