Reference composite primary key of an Entity in Typeorm

Viewed 1830

I have the following entities:

@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 will have the following error: Foreign key can not be implemented. I think the problem here is the User entity needs to reference only the id of Group, but Group has a composite primary key instead and hence the error. Removing the composite primary key in Group will solve the problem, but is there any other way to do it. I've tried the below but no luck:

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

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


1 Answers

I also use composite keys with TypeORM and encountered some trouble. Please explain me why do you add groupName to the primary key if you already have an auto-generated unique id? Wouldn't you rather want a simple primary key on id and a unique constraint on groupName?

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

  @Column({ unique: true })
  groupName: string

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