javascript - Realm JavaScript 中的一对一关系仅适用于一种模式吗?

标签 javascript reactjs react-native realm

我正在尝试使用 To-One Relationships method 将我的嵌套对象插入到 Realm 中, 但我得到了一个意想不到的结果,我的嵌套对象的所有值都与我的第一个嵌套对象的值相同 Relationship

这是我的模式

const PhotoSchema = {
  name: 'CUSTOMER_PHOTOS',
  properties: {
    base64: 'string'
  }
};

const TimeSchema = {
  name: 'CUSTOMER_TIMES',
  properties: {
    warranty: 'float',
    finish: 'float'
  }
};

const MainSchema = {
  name: 'CUSTOMERS',
  primaryKey: 'id',
  properties: {
    id: 'int',
    name: 'string',
    photo: {type: 'CUSTOMER_PHOTOS'},
    time: {type: 'CUSTOMER_TIMES'},
  }
};

并尝试像这样插入一些数据

import Realm from 'realm';

Realm.open({
  path: 'mydb.realm',
  schema: [PhotoSchema, TimeSchema, MainSchema]
})
.then((realm) => {

  realm.write(() => {
    realm.create('CUSTOMERS', {
      id: Date.now(),
      name: 'John',
      photo: {
        base64: 'ImageBase64'
      },
      time: {
        warranty: 31,
        finish: 7
      }
    })
  })

})
.catch((error) => {
  console.error(error)
});

插入数据的过程是成功的但是当成功从 Realm 获取数据时我得到了意外的结果

console.log() 中的意外结果

{
  id: 1601335000882,
  name: "John",
  photo: {
    base64: "ImageBase64"
  },
  // This value is the same as PhotoSchema
  time: {
    base64: "ImageBase64"
  }
}

我想要这样的实际结果

{
  id: 1601335000882,
  name: "John",
  photo: {
    base64: "ImageBase64"
  },
  time: {
    warranty: 21
    finish: 7
  }
}

我的代码有什么问题吗? Documentation方法不太详细,解释和例子一言以蔽之

更新:

我只在 console.log() 中得到了意外结果,如果我尝试像 MY_DATA.time.warranty 一样直接访问该属性,结果就是我预计

答案是:否

To-One Relationships method不仅针对一个Schema,而且感谢 Angular San用于显示反向关系方法的示例。

最佳答案

尝试反向关系

我用 Inverse Relationships 得到了预期的结果方法。在此方法中,您必须添加一个连接到主架构的属性,我想将其称为 combiner 属性

const PhotoSchema = {
  name: 'CUSTOMER_PHOTOS',
  properties: {
    base64: 'string',
    combiner: {type: 'linkingObjects', objectType: 'CUSTOMERS', property: 'photo'}
  }
};

const TimeSchema = {
  name: 'CUSTOMER_TIMES',
  properties: {
    warranty: 'float',
    finish: 'float',
    combiner: {type: 'linkingObjects', objectType: 'CUSTOMERS', property: 'time'}
  }
};

const MainSchema = {
  name: 'CUSTOMERS',
  primaryKey: 'id',
  properties: {
    id: 'int',
    name: 'string',
    photo: 'CUSTOMER_PHOTOS',
    time: 'CUSTOMER_TIMES',
  }
};

关于javascript - Realm JavaScript 中的一对一关系仅适用于一种模式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64111088/

相关文章:

javascript - React prop 的本地副本是只读的

javascript - 如何使用 ApolloClient 记录 HTTP 请求和响应

javascript - 如何从嵌套对象生成查询字符串

javascript - 检查 React Native 中是否始终启用位置服务(iOS 和 Android 均如此)

javascript - 如何将类数组B+树转换为类哈希B+搜索树?

javascript - CKEditor - insertText 在 setData 后不工作

javascript - 在 MUI 输入组件区域外单击时将焦点设置在该组件上

ios - 如何在 ios 中点击通知时接收数据,当应用程序被杀死时,(react-native-fcm 模块在 IOS 中获取推送通知)

react-native - 如何在 React Native 中使用有限数量的数组中的数据使平面列表无限滚动

javascript - 如何在 Java 中使用 Selenium 获取 Canvas 元素内图像的 URL,以及如何使用 JavascriptExecutor?