Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

664
Views
¿Cuál es la mejor manera de guardar relaciones de Muchos a Muchos usando TypeORM y NestJS?

Así que tengo dos entidades, User y Role con una relación Many-To-Many entre ellos.

user.entity.ts

 @Entity() @ObjectType() export class User { @PrimaryGeneratedColumn('uuid') @Field(() => String) id: string; @Field(() => String) @Column() name!: string; @Field(() => [Role]) @ManyToMany(() => Role, (role) => role.users, { cascade: true, lazy: true, }) @JoinTable() roles!: Array<Role>; } // Deleting the unnecessary properties for readability


role.entity.ts

 @Entity() @ObjectType() export class Role { @PrimaryGeneratedColumn('uuid') @Field(() => String) id: string; @Field(() => String) @Column() name!: string; @Field(() => [User]) @ManyToMany(() => User, (user) => user.roles, { lazy: true, }) users: Promise<Array<User>>; @Field(() => String) @CreateDateColumn() createdAt: Date; }

El problema al que me enfrento es que cuando tengo que crear un nuevo usuario, primero tengo que extraer las identificaciones de rol del DTO, buscar para cada identificación el objeto de rol en la base de datos y luego conectarlo al objeto de usuario manualmente antes de guardar.

 const {roleIds} = createUserInput; const roles = roleIds.map(async (id) => await roleService.findById(id)) const user = this.userRepository.create({...createUserInput, roles}); return this.userRepository.save(user);

Y todo esto funciona bien, pero tengo curiosidad por saber si hay una manera de hacer que esto funcione sin hacer llamadas adicionales y cableado manual. Si puedo pasar los roleIds y mágicamente lo resuelve automáticamente. Algo como esto:

 const user = this.userRepository.create({...createUserInput, roleIds});
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!