Search code examples
typeormnest

create a primary key for a one-to-one relationship


Background:

Since any unique entity data is a candidate key to a table, any data column constrained as unique is a candidate key. What is the syntax for a foreign key to be constrained as unique and a primary key. E.g. I have entities:

@Entity()
export class A extends BaseEntity {
  PrimaryColumn()
  id: number;
}  
  
@Entity()
export class B extends BaseEntity() {
  @OneToOne(() => A) <---- need to set this foreign key unique and the primary key of B
  @JoinColumn()
  a: A;
}  
  

As marked above, I'd like the foreign key to be unique and the primary key of B.

What I've tried so far:

I thought I had found the solution, but this syntax seems outdated; the RelationOptions does not contain the primary property:

@OneToOne( type => A, {primary: true})
@JoinColumn()
a: A

Also, it does seem possible to mark a column as unique using the @Unique decorator, but, would like to know if there's a better approach to making the column unique in this case.


Solution

  • Watch out for changes here: Typeorm changelogs

    primary relation (e.g. @ManyToOne(() => User, { primary: true }) user: User) support is removed. You still have an ability to use foreign keys as your primary keys, however now you must explicitly define a column marked as primary.

    Example, before:

    @ManyToOne(() => User, { primary: true })
    user: User
    

    Now:

    @PrimaryColumn()
    userId: number
    
    @ManyToOne(() => User)
    user: User
    

    Primary column name must match the relation name + join column name on related entity. If related entity has multiple primary keys, and you want to point to multiple primary keys, you can define multiple primary columns the same way:

    @PrimaryColumn()
    userFirstName: string
    
    @PrimaryColumn()
    userLastName: string
    
    @ManyToOne(() => User)
    user: User