我正在尝试使用 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/