【问题标题】:Is To-One Relationships in Realm JavaScript only for one schema?Realm JavaScript 中的一对一关系是否仅适用于一种模式?
【发布时间】:2025-12-21 18:20:28
【问题描述】:

大家好

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

这是我的架构的样子

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 展示了一个反向关系方法的示例。

【问题讨论】:

    标签: javascript reactjs react-native realm


    【解决方案1】:

    尝试反向关系

    我使用Inverse Relationships 方法得到了预期的结果。在这种方法中,您必须添加一个连接到 Main Schema 的属性,我想将其称为 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',
      }
    };
    

    【讨论】:

    • 哦!我认为Inverse Relationships 方法仅适用于list [] 类型,我很困惑如何使用该方法,因为文档中的示例对我来说不是太详细,而且我的英语仍然很差,但是,非常感谢!