Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeORM: How to define nested data relationships?

I am looking at using TypeORM for a new project (TypeScript + express).

How can I define a nested relationship?

Here's an example of the data structure:

Topic:
{
  applicationId: 2,
  name: 'test',
  recipients: [
    {
      id: 1,
      transports: [
        {
          id: 1,
          templateId: 1,
        },
        {
          id: 2,
          templateId: 1,
        },
      ],
    },
    {
      id: 2,
      transports: [
        {
          id: 1,
          templateId: 4,
        },
      ],
    },
  ],
  startTime: null,
}

A Topic can have 1 or more Recipients. For each Recipient, there is 1 or more Transports.

Currently I am defining the relationship with a single join table:

CREATE TABLE topics_recipients_transports
(
  id          INT IDENTITY PRIMARY KEY,
  topicId     INT NOT NULL REFERENCES topics,
  recipientId INT NOT NULL REFERENCES recipients,
  transportId INT NOT NULL REFERENCES transports,
  templateId  INT NOT NULL REFERENCES templates,
  config      NVARCHAR(MAX)
)
GO

CREATE UNIQUE INDEX topics_recipients_transports_unique
  ON topics_recipients_transports (topicId, recipientId, transportId)
GO

As you can see, the relationship is one-to-many from Topic -> Recipient -> Transport but the relationship from Transport -> Recipient is dependent on the Recipient -> Topic association.

like image 427
Chris Thompson Avatar asked Jul 31 '26 09:07

Chris Thompson


1 Answers

Nested relationship can be defined as:

this.topicRepo.find({ relations: ["recipients", "recipients.transports"] });
like image 173
n_saad Avatar answered Aug 03 '26 01:08

n_saad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!