...

/

Handling Many-to-Many Relationships

Handling Many-to-Many Relationships

Learn and practice handling many-to-many relationships.

A many-to-many relationship

In this lesson, we’ll learn how to manage many-to-many relationships using TypeORM.

A many-to-many relationship is typical when dealing with complex data structures. Below is an example of the user and role entities. A user entity can have multiple roles to define their access, and a role entity can be assigned to multiple users.

Press + to interact
A many-to-many relationship between user and role
A many-to-many relationship between user and role

In the illustration above, there is a user-roles-role intermediate table. It’s to link the primary keys of the user and role tables.

Define the entities

First, we need to define the user and role entities.

Press + to interact
// user.entity.ts
@Entity('user')
export class UserEntity {
@PrimaryGeneratedColumn()
id: number;
...
@ManyToMany(() => RoleEntity, (role) => role.users, {
eager: true,
cascade: ['insert', 'update'],
})
@JoinTable()
roles: RoleEntity[];
}
// role.entity.ts
@Entity('role')
export class RoleEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@ManyToMany(() => UserEntity, user => user.roles, {
cascade: ['insert', 'update'],
})
users: UserEntity[];
}

Two decorators are used to define the many-to-many relationship between the two entities.

  • @ManyToMany: This specifies the many-to-many relationship between ...