简体   繁体   English

如何在 realmjs 中引用 object

[英]How to reference an object in realmjs

If i have two related realm objects, eg:如果我有两个相关的 realm 对象,例如:

    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...我需要创建一辆汽车并直接引用车主,而无需经过人员 object 并推动新创建的汽车......

EG:例如:

    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)我怎样才能将所有者 object 直接链接到汽车而不是: owner.cars.push(car)

Any help PLZ !任何帮助PLZ!

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.列表是托管对象的一对多关系,列表存储为父 object 的托管属性。

LinkingObjects on the other hand is more of a "computed property";另一方面,LinkingObjects 更像是一种“计算属性”; 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.它们的内容不被管理或存储在磁盘上——它们的值以更实时的方式从现有的托管对象中提取——在概念上类似于计算属性。

eg when an object that has a LinkingObjects property is added to a list, its linkingObjects property automagically has a reference to that parent object例如,当将具有 LinkingObjects 属性的 object 添加到列表时,其 linkingObjects 属性会自动引用该父项 object

So 'adding' an object directly to a LinkingObjects is not possible.因此,将 object 直接“添加”到 LinkingObjects 是不可能的。

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.此设置将允许随时将一个人添加到 Car 中,请记住,在将汽车手动添加到该人的Car[]列表之前,此人不会拥有他们的汽车列表。 That being said, it could be queried话虽这么说,它可以查询

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

but a List is much more convenient.但 List 更方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM