react-native - Realm 和 React Native 启用使用嵌套对象的主键更新对象

标签 react-native realm

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

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

错误:尝试使用现有主键值创建“类别”类型的对象

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

这是我的结构

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

最佳答案

我的猜测是您从这一行收到此错误:

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

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

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

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

关于react-native - Realm 和 React Native 启用使用嵌套对象的主键更新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38616252/

相关文章:

javascript - 如何在 React Native 中绘制虚线边框样式

java - 如何理解 Realm 在 android 上的行为?

ios - 我如何防止 RealmSwift 列表中出现重复项?

swift - 带有 AnyObject 下标的 Realm.io

javascript - React Native 某些样式导致 View 无法渲染

android - 让 Android RecyclerView 更新 React Native 组件内的 View

android - 在 Realm 中执行简单的迁移

ios - Realm :请展示如何正确创建对象

ios - 在 native react 中动态需要 json 文件(来自数千个文件)

android - 无法使用 react-native 为 android 构建