Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
Datos del modelo

Relaciones y objetos incrustados - React Native SDK

Una relación uno a uno significa que un objeto se relaciona con como máximo un objeto de un tipo en particular. Para definir una relación uno a uno, especifica el tipo de propiedad como el tipo de objeto Realm relacionado.

Ejemplo

En este ejemplo, un Manufacturer puede hacer un solo Car:

class ToOneManufacturer extends Realm.Object {
_id!: BSON.ObjectId;
name!: string;
car?: Car;
static schema: Realm.ObjectSchema = {
name: 'ToOneManufacturer',
properties: {
_id: 'objectId',
name: 'string',
// A manufacturer that may have one Car object
car: 'Car?',
},
};
}
class Car extends Realm.Object {
_id!: BSON.ObjectId;
model!: string;
miles?: number;
static schema: Realm.ObjectSchema = {
name: 'Car',
properties: {
_id: 'objectId',
model: 'string',
miles: 'int?',
},
};
}

A one-to-many relationship means an object may be related to multiple objects. To define a to-many relationship, specify a property where the type is a list or array of the related Realm object type in its object schema.

Ejemplo

In this example, a Manufacturer may make many Car models:

class ToManyManufacturer extends Realm.Object {
_id!: BSON.ObjectId;
name!: string;
cars!: Realm.List<LinkedCar>;
static schema: Realm.ObjectSchema = {
name: 'ToManyManufacturer',
properties: {
_id: 'objectId',
name: 'string',
// A manufacturer's related LinkedCar objects
cars: 'LinkedCar[]',
},
};
}
class LinkedCar extends Realm.Object {
_id!: BSON.ObjectId;
model!: string;
miles?: number;
static schema: Realm.ObjectSchema = {
name: 'LinkedCar',
properties: {
_id: 'objectId',
model: 'string',
miles: 'int?',
// A car's related ToManyManufacturer objects
manufacturer: {
type: 'linkingObjects',
objectType: 'ToManyManufacturer',
property: 'cars',
},
},
};
}

An inverse relationship links an object back to any other objects that refer to it in a defined to-one or to-many relationship. Relationship definitions are unidirectional by default. You must explicitly define a property in the object's model as an inverse relationship.

For example, the to-many relationship "Manufacturer has many Cars" does not automatically create the inverse relationship "Car belongs to Manufacturer". If you don't specify the inverse relationship in the object model, you need to run a separate query to look up the manufacturer who makes a car.

Puedes asignar una relación inversa a una propiedad en el esquema de objetos usando linkingObjects. Esto te permite acceder a la relación inversa como una propiedad normal.

Una propiedad linkingObjects crea vínculos inversos hacia una relación específica. Se especifica a qué hacer vínculo inverso con el tipo de objeto Realm y el nombre de la propiedad de la relación.

Ejemplo

En este ejemplo, la propiedad cars del objeto ManufacturerInverse tiene una relación de muchos con un Lista de CarInverse objetos. Contiene todos los coches vinculados al fabricante.

The CarInverse object's manufacturer property inverts this relationship. The manufacturer property automatically updates to refer back to any ManufacturerInverse object that contains the car object in its cars property.

class ManufacturerInverse extends Realm.Object {
_id!: BSON.ObjectId;
name!: string;
cars!: Realm.List<CarInverse>;
static schema: Realm.ObjectSchema = {
name: 'ManufacturerInverse',
properties: {
_id: 'objectId',
name: 'string',
// A manufacturer's related CarInverse objects
cars: 'CarInverse[]',
},
};
}
class CarInverse extends Realm.Object {
_id!: BSON.ObjectId;
model!: string;
manufacturer!: Realm.List<ManufacturerInverse>;
miles?: number;
static schema: Realm.ObjectSchema = {
name: 'CarInverse',
properties: {
_id: 'objectId',
model: 'string',
miles: 'int?',
// A car's related ManufacturerInverse objects
manufacturer: {
type: 'linkingObjects',
objectType: 'ManufacturerInverse',
property: 'cars',
},
},
};
}

Se pueden encontrar todos los objetos que están vinculados a un objeto en particular llamando al Realm.Object.linkingObjects() del objeto. método. Esto es útil cuando se desea acceder a todos los objetos vinculados de una relación en particular sin agregar una propiedad al esquema del objeto.

Ejemplo

En este ejemplo, tenemos un modelo de objeto LinkedCar que no tiene un campo manufacturer de tipo 'linkingObjects'. Se crean varios fabricantes y objetos de coche, añadiendo los coches recién creados al campo cars de un fabricante.

We can find a car's manufacturer using the linkingObjects() method. This method returns a Results collection of objects that link to the car. In this example, only one manufacturer makes the Sentra car model, so we can expect that manufacturer to be named Nissan.

Para encontrar el fabricante que produce un auto específico:

  1. Call linkingObjects()

  2. Pass the manufacturer class name and "cars" field as parameters

const getLinkedManufacturer = (car: LinkedCar): string => {
const manufacturer = car.linkingObjects<ToManyManufacturer>(
'ToManyManufacturer',
'cars',
)[0];
// Returns 'Nissan', as only one manufacturer is linked
// to this car object.
return manufacturer.name;
};

Un objeto incrustado es un tipo especial de objeto Realm que modela datos complejos sobre un objeto específico. Los objetos incrustados son similares a las relaciones, pero proporcionan restricciones adicionales y se mapean de forma más natural al modelo orientado a documentos denormalizado de MongoDB.

Realm aplica restricciones de propiedad únicas que tratan cada objeto incrustado como datos anidados dentro de un único objeto principal específico. Un objeto incrustado hereda el ciclo de vida de su objeto principal y no puede existir como un objeto independiente de Realm. Esto significa que los objetos incrustados no pueden tener una clave principal y que Realm los elimina automáticamente si se elimina su objeto principal.

Tip

Embedded object types are reusable and composable

You can use the same embedded object type in multiple parent object types, and you can embed objects inside other embedded objects. You can even recursively reference an embedded object type as an optional property in its own definition.

Nota

Realm Uses Cascading Deletes for Embedded Objects

When you delete a Realm object, Realm automatically deletes any embedded objects referenced by that object. Any objects that your application must persist after the deletion of their parent object should use relationships instead.

To define an embedded object, set embedded to true. You can reference an embedded object type from parent object types in the same way you define a relationship:

class Manufacturer extends Realm.Object {
_id!: BSON.ObjectId;
name!: string;
cars!: Realm.List<CarWithEmbed>;
warranties!: Realm.List<Warranty>;
static schema: Realm.ObjectSchema = {
name: 'Manufacturer',
properties: {
_id: 'objectId',
name: 'string',
cars: 'CarWithEmbed[]',
// Embed an array of objects
warranties: 'Warranty[]',
},
};
}
class CarWithEmbed extends Realm.Object {
_id!: BSON.ObjectId;
model!: string;
miles?: number;
warranty?: Warranty;
static schema: Realm.ObjectSchema = {
name: 'CarWithEmbed',
properties: {
_id: 'objectId',
model: 'string',
miles: 'int?',
// Embed one object
warranty: 'Warranty?',
},
};
}
class Warranty extends Realm.Object {
name!: string;
termLength!: number;
cost!: number;
static schema: Realm.ObjectSchema = {
name: 'Warranty',
embedded: true,
properties: {
name: 'string',
termLength: 'int',
cost: 'int',
},
};
}

Importante

Embedded objects can't have a primary key.

Volver

Define un modelo de objeto

En esta página