【发布时间】: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