typeorm nestjs many to many relationship insert intermediate table

Viewed 301

I am new to NestJs and I am stuck on a problem with inserting objects from my backend.

The problem when I save platform I also save the projects and choose the type and technologies of projects.

Result ==> platform and project insert in database but the intermediate table technolgies_projects is not modified.

The code below.

// platform.entity.ts

@Entity('platforms')
 export class Platform extends BaseEntity {
   @PrimaryGeneratedColumn()
   readonly id!: number;
 
   @Column()
   @Index({ unique: true })
   name!: string;
 
   // Relation one to many between project and platform (platform can have many projects)
   @OneToMany(() => Project, (projects) => projects.platform, {
     cascade: ['insert'],
   })
   projects!: Project[];
 
 }

// project.entity.ts

@Entity({ name: 'projects' })
export class Project extends BaseEntity {
  @PrimaryGeneratedColumn()
  readonly id!: number;

  @Column({ type: String })
  name!: string;


  // Relation many to one between project and platform (many projects can have one platform)
  @ManyToOne(() => Platform, (platform) => platform.projects)
  platform!: Platform;

  // Relation many to many between projects and technologies
  @ManyToMany(() => Technology, (technologies) => technologies.id)
  @JoinTable({
    name: 'technologies_projects',
  })
  technologies!: Technology[];
}

// technology.entity.ts

export class Technology extends BaseEntity {
  @PrimaryGeneratedColumn()
  readonly id!: number;

  @Column({ length: 64 })
  @Index({ unique: true })
  name!: string;

  // Relation many to many between projects and technologies
  @ManyToMany(() => Project)
  projects!: Project[];

  // Relation one to many between  types and technology (technology can have many types)
  @ManyToOne(() => ProjectType, (type) => type.technologies, {
    cascade: ['insert'],
  })
  type!: ProjectType;
}

// platform.service.ts

async create(request: CreatePlatformRequestDto) {
    const projects = request.types.map((e) => {
      return {
        name: e.name,         <--- this name project
        type: { id: e.id },      <--- this id type of projects
        technologies: Array.from(e.technologies, (technology) => {   <-- this technologies of projects
          return { name: technology, type: { id: e.id } };
        }),
      };
    });

    const platform: DeepPartial<Platform> = {
      name: request.name,
      projects,
    };
    return this.platformsRepository.save(platform);
  } 
0 Answers
Related