【问题标题】:Realm and react Native Enable Updating Objects With Primary Keys for Nested Objects领域和反应本机启用使用嵌套对象的主键更新对象
【发布时间】:2016-12-01 15:48:13
【问题描述】:

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

对于第一个实例,我创建领域对象并使用主键传递 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'
  }
};

这就是我坚持数据库的方式

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

【问题讨论】:

    标签: react-native realm


    【解决方案1】:

    我猜你会从这一行得到这个错误:

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

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

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

    这将重用现有类别(如果存在),或者创建它们(如果不存在)。

    【讨论】:

    • 我收到以下错误Error: 'Property' must be of type: string
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多