Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference on already created object in Realm?

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?

like image 887
acidernt Avatar asked Sep 02 '25 15:09

acidernt


1 Answers

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,
});
like image 54
marius Avatar answered Sep 04 '25 07:09

marius