【问题标题】:Reference composite primary key of an Entity in Typeorm在 Typeorm 中引用实体的复合主键
【发布时间】:2021-03-25 14:50:46
【问题描述】:

我有以下实体:

@Entity()
class Group {
  @PrimaryGeneratedColumn()
  id: string

  @PrimaryColumn()
  groupName: string

  @OneToMany(() => User, user => user.group)
  user: User[]
}

@Entity()
class User {
  @PrimaryGeneratedColumn()
  id: string

  @ManyToOne(() => Group)
  group: Group
}

Typeorm 会出现如下错误:无法实现外键。我认为这里的问题是用户实体只需要引用 Group 的 id,但是 Group 有一个复合主键,因此出现了错误。删除 Group 中的复合主键会解决问题,但是有没有其他方法可以做到。我已经尝试了以下但没有运气:

@Entity()
class User {
  @PrimaryGeneratedColumn()
  id: string

  @ManyToOne(() => Group)
  @JoinColumn([
    {name: 'groupId', referencedColumnName: 'id'},
    {name: 'groupName', referencedColumnName: 'groupName'}
  ])
  group: Group
}


【问题讨论】:

    标签: javascript sql typescript typeorm


    【解决方案1】:

    我也在 TypeORM 中使用复合键,但遇到了一些麻烦。 请解释一下,如果您已经拥有自动生成的唯一 ID,为什么还要将 groupName 添加到主键? 您不想在 id 上使用简单的主键,在 groupName 上使用唯一约束吗?

    @Entity()
    class Group {
      @PrimaryGeneratedColumn()
      id: string
    
      @Column({ unique: true })
      groupName: string
    
      @OneToMany(() => User, user => user.group)
      user: User[]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      • 1970-01-01
      • 2012-03-26
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多