How to reference an object in realmjs

109 Views Asked by At

If i have two related realm objects, e.g:

    const PersonSchema = {
      name: 'Person', properties: {name: 'string', cars: 'Car[]'},
    };

    const CarSchema = {
      name: 'Car',
      properties: {model: 'string', owner: {type: 'linkingObjects', objectType: 'Person', property: 'cars'}},
    };

And i need to create a car and reference the owner directly without passing by the Person object and pushing the new created Car...

E.G:

    realm.write(() => {
        const car = realm.create('Car', {
          model: 'Model name',
          owner: ownerID
        });
    });

How can i link the owner object to the car directly instead of: owner.cars.push(car)

Any help PLZ !

1

There are 1 best solutions below

0
On BEST ANSWER

I posted this as a comment and re-reading it, it's actually the answer so I hope it helps future readers.

Lists are a one to many relationship of managed objects and the list is stored as a managed property of the parent object.

LinkingObjects on the other hand is more of a "computed property"; their contents are not managed or stored on disk - their values are pulled from existing managed objects in more of a live fashion - similar in concept to a computed property.

e.g. when an object that has a LinkingObjects property is added to a list, its linkingObjects property automagically has a reference to that parent object

So 'adding' an object directly to a LinkingObjects is not possible.

There may be other options though - creating a back link property may be one option - that would allow a one-to-many forward relationship and one to one back relationship. However, the relationship has to be manually managed and the car could only belong to one person. Some pseudo code

Person = {
   name: 'Person'
   cars: 'Car[]'
}

Car = {
   name: 'Car'
   belongsTo: Person
}

This setup would allow a person to be added to a Car at any time, keeping in mind that the person won't have a List of their cars until the car is then added to that persons Car[] list manually. That being said, it could be queried

let thisPersonsCars = realm.cars where car.belongsTo == this person

but a List is much more convenient.