Working with many-to-many relationships and inserting data in TypeORM involves several steps. I will demonstrate this process with an example.
1. Defining Entities
Assume we have two entities, User and Group, which have a many-to-many relationship. First, we need to define this relationship in both entities. In TypeORM, we can use the @ManyToMany decorator to identify this relationship and use @JoinTable to define the join table on the owning side.
typescriptimport { Entity, PrimaryGeneratedColumn, Column, ManyToMany, JoinTable } from "typeorm"; import { Group } from "./Group"; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; @ManyToMany(() => Group) @JoinTable() groups: Group[]; }
typescriptimport { Entity, PrimaryGeneratedColumn, Column, ManyToMany } from "typeorm"; import { User } from "./User"; @Entity() export class Group { @PrimaryGeneratedColumn() id: number; @Column() name: string; @ManyToMany(() => User) users: User[]; }
2. Inserting Data
When inserting data, it's important to properly handle the related entities. This typically involves the following steps:
a. Creating Entity Objects
typescriptlet user = new User(); user.name = "Alice"; let group1 = new Group(); group1.name = "Group1"; let group2 = new Group(); group2.name = "Group2";
b. Setting Relationships
Before establishing the relationship, if the records are new, we may need to save these entities first.
typescriptimport { createConnection, getRepository } from "typeorm"; async function main() { await createConnection(/*...*/); const userRepository = getRepository(User); const groupRepository = getRepository(Group); await groupRepository.save([group1, group2]); // Associate user with groups user.groups = [group1, group2]; await userRepository.save(user); }
3. Verifying Data
To verify that the data is correctly inserted, we can query existing records and check if the relationships are properly set.
typescriptasync function checkUser() { const users = await userRepository.find({ relations: ["groups"] }); console.log(users); } checkUser();
This example demonstrates how to set up many-to-many relationships and insert related data in TypeORM. In practical applications, additional scenarios may need to be handled, such as updating or deleting relationships and managing transactions.