领域和反应Native启用使用嵌套对象的主键更新对象

时间:2016-07-27 14:44:30

标签: react-native realm

如何使用主键全局启用更新对象

对于第一个实例,我创建了realm对象并使用主键传递true进行更新,它适用于根级别对象,但子对象在第二次运行时抛出错误

Error: Attempting to create an object of type 'Category' with an existing primary key value

有没有办法通过全局主键设置更新

这是我的结构

class Response extends Realm.Object {}
Response.schema = {
name: 'Response',
primaryKey: 'id',
properties: {
    id:'int',    // primary key
    categories: {type: 'list', objectType: 'CategoryList'},
  }
};
class CategoryList extends Realm.Object {}
CategoryList.schema = {
name: 'CategoryList',
properties: {
    category: {type: 'Category'},
  }
};
Category extends Realm.Object {}
Category.schema = {
primaryKey:'categoryId',
name: 'Category',
properties: {
    categoryId:'string',
    name:'string',
    itemsCount:'int',
    createdDate:'string'
  }
};

这就是我坚持使用db

的方法
    let Response = realm.objects('Response');
    let CategoryList = realm.objects('CategoryList');

        realm.write(()=>{
            realm.create('Response', {id:1,name: 'Response',categories: CategoryList},true);
            let Categories = Response[0].categories;

            for (let i=0;i<responseData.categories.length;i++){
                Categories.push(responseData.categories[i]);
            }
        });

1 个答案:

答案 0 :(得分:1)

我的猜测是你从这一行得到这个错误:

Categories.push(responseData.categories[i]);

push隐式尝试创建新类别,而不是更新/重用现有类别。尝试将其更改为:

Categories.push(realm.create('Catetory', responseData.categories[i], true));

如果现有类别存在,则会重复使用现有类别,如果不存在,则创建它们。