Complicated connections between TypeORM and MySQL

Currently leveraging TypeORM in tandem with MySQL, my database comprises of two main Entities, namely User and Project:

@Entity()
class User {
    @PrimaryGeneratedColumn('uuid') 
    id: string;  

    @Column({})
    name: string;
}

@Entity()
class Project {
    @PrimaryGeneratedColumn('uuid') 
    id: string;  

    @Column({})
    name: string;
}

In the near future, I aim to introduce a third Entity called Invitation. Each invitation is uniquely identified by the userId and projectId pair. Although a user can receive invites for multiple projects, they should only have one invite per project. Additionally, I intend to record the user responsible for sending out the invitation.

@Entity()
class Invitation {
    @PrimaryGeneratedColumn('uuid') 
    id: string;  

    @Column({})
    userID: string;

    @Column({})
    invitedById: string;

    @Column({})
    projectID: string;

    @Column({})
    otherInformations: string;

}

I am seeking advice on how to properly establish these relationships using TypeORM's Relation decorators. Any guidance would be greatly appreciated as I am relatively new to the realm of ORM development.

Wishing you all an enjoyable end to your weekend.

Answer №1

Here is the final representation:

@Entity()
class Invitation {
  @PrimaryGeneratedColumn("uuid")
  id: string;

  @Column({})
  projectID: string;

  @Column({})
  otherInformations: string;

  // Relations
  @ManyToOne(() => User, (user) => user.invitations)
  user: User;

  @ManyToOne(() => Project, (project) => project.invitations)
  project: Project;

  @ManyToOne(() => User, (user) => user.invited)
  invitedById: User;
}

@Entity()
class Project {
  @PrimaryGeneratedColumn("uuid")
  id: string;

  @Column({})
  name: string;

  @OneToMany(() => Invitation, (invitation) => invitation.project)
  invitations: Invitation[];
}

@Entity()
class User {
  @PrimaryGeneratedColumn("uuid")
  id: string;

  @Column({})
  name: string;

  @OneToMany(() => Invitation, (invitation) => invitation.user)
  invitations: Invitation[];

  @OneToMany(() => Invitation, (invitation) => invitation.invitedById)
  invited: Invitation[];
}

I am attempting to clarify it, but for a more concise explanation of the relationships, you can refer to this video tutorial: https://www.youtube.com/watch?v=8kZ7W-bI5qQ&t=239s&ab_channel=BenAwad (please disregard the graphql section) or read the relation documentation here:

Hence, your Invitation entity serves as the bridge between the User and the Project in a many-to-many relationship. The user can be accessed via the @ManyToOne() decorator, establishing a link between multiple users and a single invitation. The same methodology applies to the Project entity:

  // Invitation.ts
  @ManyToOne(() => User, (user) => user.invitations)
  user: User;

  @ManyToOne(() => Project, (project) => project.invitations)
  project: Project;

In each Entity, ensure to incorporate the corresponding relationship with the Invitation entity

  // User.ts
  @OneToMany(() => Invitation, (invitation) => invitation.user)
  invitations: Invitation[];

  @OneToMany(() => Invitation, (invitation) => invitation.invitedById)
  invited: Invitation[];

  // Project.ts
  @OneToMany(() => Invitation, (invitation) => invitation.project)
  invitations: Invitation[];

Note the use of [] due to it being a ...ToMany() relationship

invitedById should also be added similarly:

  // Invitation.ts
  @ManyToOne(() => User, (user) => user.invited)
  invitedById: User;

  // User.ts
  @OneToMany(() => Invitation, (invitation) => invitation.invitedById)
  invited: Invitation[];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to determine if a tuple is of infinite or finite length?

Is there a way to determine if a tuple is finite or infinite? I've been working on a solution, but it doesn't cover all cases: type IsFinite<T extends any[], Finite = true, Infinite = false> = T extends [] ? Finite : T extends (infer E ...

I am looking to create dynamic MySQL connections in Node.js, where the connections will vary based on the user accessing the server

I have developed an app that caters to different customers, such as customer_1 and customer_2. I have configured Sequelize in the following way: const Sequelize = require('sequelize'); const Op = Sequelize.Op; const fs = require('fs'); ...

Issue TS1192: The module named "A.module" does not contain a default export

After creating a new module 'A', I attempted to import it in another module named 'B'. However, during compilation, I encountered the following error: Error TS1192: Module '" A.module"' has no default export I wou ...

Protractor typescript guide: Clicking an element with _ngcontent and a span containing buttontext

I'm struggling with creating a protractor TypeScript code to click a button with _ngcontent and span buttontext. Does anyone have any ideas on how to achieve this? The code snippet on the site is: <span _ngcontent-c6 class="braeting net-subheadi ...

Enhance your Typescript code with a type guard that supports optional wrapped types

I haven't come across a question similar to this one before. My goal is to develop a type guard that can accurately determine the type of a specific variable. It's quite simple with a single type. type A = { id: number, title: string, type: stri ...

tips for showcasing the database on my administrator page

Once the form is submitted, all the data is sent to the SQL database. Now, my goal is to display this database data on the admin page. Below is my PHP form code: <?php // Begin the session session_start(); ?> <!DOCTYPE html> <html lang="e ...

Making a convoluted mysql query successfully execute

While I may not be an SQL expert, I have recently delved into using the sqlite3 module in conjunction with databases in Python, along with pandas and its read_sql_query() function, which have proven to be a powerful combination. Suppose we have a database ...

What are the methods to determine the cause of ESLint's slow performance?

Looking to analyze the performance of ESLint in my application. So far, I have only come across one profiling tool provided by ESLint which is the TIMING=1 environment variable. Combining this with DEBUG=eslint:cli-engine allows me to see timing results pe ...

What are the best practices for utilizing fetch() to retrieve data from a web API effectively?

Is there a way to store stock data in stockData and display it in the console upon form submission? Upon submitting the form, I only receive undefined. I suspect this may be due to a delay in fetching data from the API (but not certain). How can I resol ...

There is a WARNING occurring at line 493 in the file coreui-angular.js located in the node_modules folder. The warning states that the export 'ɵɵdefineInjectable' was not found in the '@angular/core' module

I encountered a warning message while running the ng serve command, causing the web page to display nothing. Our project utilizes the Core Ui Pro Admin Template. Here is the list of warning messages: WARNING in ./node_modules/@coreui/angular/fesm5/coreu ...

Automatically convert TypeScript packages from another workspace in Turborepo with transpilation

I have set up a Turborepo-based monorepo with my primary TypeScript application named @myscope/tsapp. This application utilizes another TypeScript package within the same repository called @myscope/tspackage. For reference, you can view the example reposit ...

Adding pixels to the top position with jQuery in Angular 2

I am trying to adjust the position of my markers when the zoom level is at 18 or higher by adding 10px upwards. However, my current approach doesn't seem to be working as expected. Can someone please assist me with this issue? You can view the code sn ...

When initially compiling Angular 5, an error (TS2339) may occur, but after a successful compilation, everything runs smoothly

In a unique scenario, I wrote code that fetches information from an API server without knowing the structure of the response fields. Once I receive the response, I need to create a form for updating the data and sending it back. To handle unknown ngModel p ...

Developing a TypeScript library for versatile features across multiple projects

My goal is to export multiple classes, some independent and others interdependent, encapsulated within a single namespace, in the form of a module for external project utilization. To achieve this, I have configured a webpack build to compile these classe ...

Ways to delete a class in typescript

There's a menu on my website with li tags containing an a element for navigation. Everything is working fine, but I'm facing an issue where I need to remove all elements with the class seleccionado and only add it to the clicked li. I tried using ...

Surprising NULL values when executing INNER JOIN in PHP/MySQL

I am currently facing an issue with my code. I am running a function that uses an inner join in a while loop, but it is unexpectedly returning nothing. $data3 = '\'' . implode('\', \'', $posted_email) . & ...

How to implement automatic scrolling to the bottom of a div in React

Currently facing an issue in React: I am looking to implement auto-scroll functionality when the page loads, so it scrolls to the bottom of the messages box. Here is my current code snippet: import Title from "components/seo/Title"; import { u ...

How can I manually listen to Angular 2 events on a dependency injected instance?

Assume I am working with a component: @Component({selector: 'todo-cmp'}) class TodoCmp { @Input() model; @Output() complete = new EventEmitter(); // TypeScript supports initializing fields onCompletedButton() { this.complete.next(); / ...

Tips for transforming an Observable stream into an Observable Array

My goal is to fetch a list of dogs from a database and return it as an Observable<Dog[]>. However, whenever I attempt to convert the incoming stream to an array by using toArray() or any other method, no data is returned when calling the retrieveDo ...

Lack of Intellisense in Sveltekit for the generated $types module on WebStorm

Is there a setting in WebStorm to enable intellisense for automatically generated ./$types by SvelteKit? I'm writing without any minimal example, just curious. Everything is done according to SvelteKit's documentation. Using satisfies LayoutLoad ...