inf*_*-vv 2 database realm react-native
让我们以官方领域文档为例。我们有汽车和人。
const CarSchema = {
name: 'Car',
properties: {
id: {type: 'string'}, // UUID
make: {type: 'string'},
model: {type: 'string'}
}
};
const PersonSchema = {
name: 'Person',
properties: {
name: {type: 'string'},
car: '' // Something here to reference on already created car??
}
};
Run Code Online (Sandbox Code Playgroud)
例如,我已经用 UUID id-s 创建了一些汽车。现在我想创建一个用户。在 UI 中,它看起来像表单,您可以在其中写入用户名并从下拉列表中选择已创建的车辆之一。
那么如何引用已经创建的汽车呢?它应该是带有 id 的字符串,还是什么?
链接在 Realm 中是一等公民,因此您无需引入人工外键。您可以直接链接到另一个对象架构。在基于 JavaScript 的绑定中,您可以通过指定相关对象模式的名称来实现这一点,type如下所示。
const PersonSchema = {
name: 'Person',
properties: {
name: { type: 'string' },
car: { type: 'Car' } // or just: 'Car'
}
};
Run Code Online (Sandbox Code Playgroud)
使用这样的模型,您可以创建Person具有现有Car附加的对象,如下所示:
const realm = …
const volvo = realm.objects("Car").filtered("make = $0 AND model = $1", "Volvo", "XC60")[0];
const person = realm.create("Person", {
name: "Tim",
car: volvo,
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1065 次 |
| 最近记录: |