【问题标题】:TypeORM many to many relationship give duplicate row when savingTypeORM 多对多关系在保存时给出重复行
【发布时间】:2021-05-11 18:33:52
【问题描述】:

假设我有一些这样的实体

项目实体

@Entity()
export class ProjectEntity {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

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

}

标记实体

@Entity()
export class TagEntity {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

}

项目标签实体


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

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

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

  @CreateDateColumn()
  createdAt: Date;
}

当我像这样保存它们时:

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

为什么 project_tag 表中有重复的行?例如,以前已经存在与项目的 tag1 和 tag2 关系,但我第二次保存它,它在 project_tag 表中给出了重复的行。我该如何避免这种行为?

【问题讨论】:

    标签: typescript nestjs typeorm


    【解决方案1】:

    我没有看到项目和类别之间的关系是在哪里定义的。此外,您不需要将标签键入为Promise&lt;TagEntity[]&gt;。你应该可以输入简单的TagEntity[]

    【讨论】:

    • 我想延迟加载这种行为,但我肯定也尝试过TagEntity[],但仍然重复。我将项目标签实体添加到描述中
    【解决方案2】:

    检查数据表和连接表中的 id 列。它们应该具有相同的类型。我有这样的问题,就是这样。

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    • 谢谢我重新检查,你的建议是真的
    猜你喜欢
    • 2021-10-18
    • 1970-01-01
    • 2019-04-24
    • 2020-06-29
    • 2011-01-21
    • 2020-08-29
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    相关资源
    最近更新 更多