Puedes hacer referencia a otros modelos de Realm desde tu modelo de Realm. Esto permite crear los siguientes tipos de relaciones entre objetos Realm:
También puede insertar un objeto Realm directamente dentro de otro para crear una estructura de datos anidada. Los objetos incrustados son similares a las relaciones, pero proporcionan restricciones adicionales. Para obtener más información sobre estas restricciones y cómo crear objetos incrustados, consulta la documentación del tipo de dato Objeto incrustado.
Tip
Consultar objetos relacionados
En Flutter v1.9.0 y posteriores, puedes usar getBacklinks()Método para encontrar objetos vinculados mediante una relación. Para más información, consulte Consultar objetos relacionados.
To-One Relationship
A to-one relationship means that an object is related in a specific way to no more than one other object.
To set up a to-one relationship, create a property in your model whose type is another model. Multiple objects can reference the same object.
Importante
To-one relationships must be optional
When you declare a to-one relationship in your object model, it must be an optional property. If you try to make a to-one relationship required, Realm throws an exception at runtime.
() class _Bike { () late ObjectId id; late String name; late _Person? owner; } () class _Person { () late ObjectId id; late String firstName; late String lastName; late int? age; }
Relación de muchos
A to-many relationship means that an object is related in a specific way to multiple objects.
Puede crear una relación entre un objeto y cualquier número de objetos utilizando una propiedad de tipo List<T> en su aplicación, donde T es una clase de modelo Realm.
() class _Scooter { () late ObjectId id; late String name; late _Person? owner; } () class _ScooterShop { () late ObjectId id; late String name; late List<_Scooter> scooters; }
Relación inversa
An inverse relationship links a Realm object back to any other realm objects that refer to it in to-one or to-many relationships.
Inverse relationships have the following properties:
You must explicitly define a property in the object's model as an inverse relationship. The schema cannot infer the inverse relationship.
Inverse relationships automatically update themselves with corresponding backlinks. You can find the same set of Realm objects with a manual query, but the inverse relationship field reduces boilerplate query code and capacity for error.
No se puede establecer manualmente el valor de una propiedad de relación inversa. En su lugar, Realm actualiza las relaciones implícitas cuando se agrega o elimina un objeto en la relación.
Backlinks only work with Realm objects. Objects that haven't been added to a realm yet do not have backlinks.
For example, the to-many relationship "a User has many Tasks" does not automatically create the inverse relationship "a Task belongs to one User". If you don't specify the inverse relationship in the Task object model, you need to run a separate query to look up the user that is assigned to a given task.
Use the Backlink property annotation to define an inverse relationship. Pass a Symbol of the field name of the to-one or to-many field for which you are creating the backlink as an argument to Backlink(). Include an Iterable of the object model you are backlinking to in the field below the annotation.
() class _User { () late ObjectId id; late String username; // One-to-many relationship that the backlink is created for below. late List<_Task> tasks; } () class _Task { () late ObjectId id; late String description; late bool isComplete; // Backlink field. Links back to the `tasks` property in the `_User` model. (#tasks) late Iterable<_User> linkedUser; }
Nota
Inverse Relationships Not Present in Device Sync Schema
If you are using Atlas Device Sync, inverse relationships are not present in the server-side Device Sync schema in your App Services App. Since you can't directly set the value of an inverse relationship, the relationship does not exist in Device Sync schema.
For more information on the server-side Device Sync schema, refer to Configure and Update Your Data Model in the Atlas App Services documentation.