Relationships
There are several methods for linking related data items and organizing them for easy lookup:
- Embedded JSON object that acts as a REGISTER type or an embedded MAP. (See Key-Value Relationships)
For an example demonstrating both the deeply embedded and flat models, see Complex Structures.
Overview
The following table provides a complete overview of the different relationships you can form in Ditto, as well as a brief description, list of possible approaches you can take, and links to related content:
Relationship | Description | Approaches |
|---|---|---|
One-to-many | Associates a parent element with children elements to establish a hierarchy. |
|
Many-to-many | Associates multiple entities in one collection with multiple entities in another collection. |
|
Many-to-one | Associates two or more collections, where one collection refers to the primary key of another collection to create a meaningful relationship between the datasets. |
|
Foreign-Key Relationships
To create a foreign-key relationship, store the primary key to one document in another document.
A foreign-key relationship establishes a link between two or more datasets. For example, the following snippet demonstrates a foreign-key relationship between documents in the cars and people collections, in which the reference to susanId serves as the foreign key establishing a relationship between cars and people:
const results = await ditto.store.write(async (transaction) => {
// Create a person named Susan in the "people" collection
const cars = transaction.scoped('cars')
const people = transaction.scoped('people')
// Create a car document in the "cars" collection
const susanId = await people.upsert({
name: 'Susan',
})
await cars.upsert({
make: 'Hyundai',
color: 'red',
owner: susanId, // Set the owner field to Susan's ID
})
// Evict the Susan document from the "people" collection
await people.findByID(susanId).evict()
})Key-Value Relationships
A key-value relationship establishes a parent-child hierarchy between embedded data elements. In this hierarchy, the key functions as the parent, and its encapsulated values, represented as a set of key-value pairs, serve as children.