Wildan Dicky Alnatara
Wildan Dicky Alnatara

Reputation: 15

TypeORM many to many relationship give duplicate row when saving

Let's say I have some entities like this

Project Entity

@Entity()
export class ProjectEntity {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @ManyToMany(() => TagEntity)
    @JoinTable({ name: 'project_tag' })
    tags: Promise<TagEntity[]>;

}

Tag Entity

@Entity()
export class TagEntity {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

}

Project Tag Entity


@Entity('project_tag')
export class ProjectTagEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({
    nullable: false,
  })
  tagId: number;

  @Column({
    nullable: false,
  })
  projectId: number;

  @CreateDateColumn()
  createdAt: Date;
}

when I save them such as like this:

//assume there is already saved row for project and tag entities right here
project.categories = [tag1, tag2];
await connection.manager.save(project);

why there are duplicate rows in project_tag table? for example previously there are already exist tag1 and tag2 relationship with the project but I save it for the second time and it gives duplicate rows in project_tag table. How do I able avoid this behaviour?

Upvotes: 1

Views: 2463

Answers (2)

Vsevolod Yefremov
Vsevolod Yefremov

Reputation: 26

Check your id-columns in data-tables and in join-table. They should have same type. I had such problem and this was the case.

Upvotes: 1

C. Anikwe
C. Anikwe

Reputation: 29

I'm not seeing where the relationship between project and categories is defined. Also, you shouldn't need to type tags as Promise<TagEntity[]>. You should be able to type is simply as TagEntity[].

Upvotes: 0

Related Questions