Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

672
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda