Relationships

This is the official documentation of Forest Admin Cloud.

In Forest Admin, relationships link Collections, structuring data into a interconnected architecture beyond simple presentations.

By default, relationships are automatically discovered and configured from the connected data sources, eliminating the need for manual definition.

However, you can also create custom relationships between two different collections, from possibly separate data sources. This lets Forest Admin handle these links as if they were built-in.

The following sections assume that you have correctly followed all the steps in the Code Customization Getting Started guide.


To make the code easier to read, all the code snippets below should be wrapped in the following code. Ensure you update the collection name as needed.

import type { Agent } from '@forestadmin/forest-cloud';
import { Schema } from '../typings';

export default function customizeAgent(agent: Agent<Schema>) {
  agent.customizeCollection('towns', collection =>
    // Insert the code snippet here.
  );
}

Adding a ManyToOne relationship

To create a ManyToOne relationship, consider the scenario where each town belongs to one country. The relationships can be defined as follows:

collection.addManyToOneRelation('country', 'countries', { foreignKey: 'country_id' });

Adding a OneToMany relationship

To create a OneToMany relationship, think about how a town can have multiple residents. You can set up this relationship as follows:

collection.addOneToManyRelation('residents', 'people', { originKey: 'town_id' });

Adding a ManyToMany collection

To create a ManyToMany relationship, let's imagine a town's electricity comes from shared power plants, servicing multiple towns.

collection.addManyToManyRelation('energyProviders', 'powerPlants', 'utilityContracts', {
  originKey: 'town_id',
  foreignKey: 'power_plant_id',
});

Adding an External Relationship fed by an API

In this example, we demonstrate using an external API to retrieve data about a town with several honorary citizens. Start by defining the JSON schema returned by the API. Then use listRecords() to implement how to fetch the data.

collection.addExternalRelation('honoraryCitizen', {
  schema: { firstName: 'String', lastName: 'String' },
  listRecords: async ({ id }) => {
    const response = await axios.get(`https://api.mytown.com/cities/${id}/honorary-citizen`);
    return response.body;
  },
});

Last updated