TypeORM bidirectional composite primary key relations

4k views Asked by At

One User can have multiple Profiles. In the User I only want to store the profileId. In the Profile I want to store the id of the User.

User

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

  @Column({ nullable: true })
  public profileId?: string;

  @OneToOne(
    type => Profile,
    profile => profile.user
  )
  @JoinColumn()
  profile: Profile;
}

Profile

@Entity()
export class Profile {
  @PrimaryGeneratedColumn()
  id: string;

  @PrimaryColumn()
  userId: string;

  @OneToOne(
    type => User,
    user => user.profile
  )
  user: User;
}

In simple words I want to create two foreign keys. From User.profileId to the Profile.id and from Profile.userId to the User.Id. Is this the best practise solution for my problem?

0

There are 0 answers