Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

665
Vistas
Whats the best way to save Many to Many relationships using TypeORM and NestJS?

So I have two entities, User and Role with Many-To-Many relationship between them.

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;
}

The problem I am facing is that when I have to create a new User, I have to first extract the role ids from the DTO, fetch for each ID the role object in the database and then wire it to the user object manually before saving.

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);

And this is all working fine, but I just am curious if there is a way to get this to work without making the extra calls and manual wiring. If I can just pass in the roleIds and it magically auto resolves it. Something like this:

const user = this.userRepository.create({...createUserInput, roleIds});
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda