Reputation: 2311
Let's take example from official realm docs. We have Cars and Persons.
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??
}
};
For example I already created some cars with UUID id-s. Now I want to create a user. In UI it will look like form, where you write user name and pick from dropdown one of the already created vehicles.
So how to reference on already created car? It should be string with id, or what?
Upvotes: 4
Views: 1701
Reputation: 7806
Links are first-class citizen in Realm, so that you don't need to introduce an artificial foreign-key. You can just link to another object schema directly. In the JavaScript-based bindings, you achieve that by specifying the name of the related object schema as type
as seen below.
const PersonSchema = {
name: 'Person',
properties: {
name: { type: 'string' },
car: { type: 'Car' } // or just: 'Car'
}
};
With such model you can create Person
objects with an already existing Car
attached as seen below:
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,
});
Upvotes: 7