1

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?

dewey
  • 809
  • 2
  • 16
  • 47
  • Having bi-directional FKs can be a maintenance nightmare. Without extenuating circumstances there is no need for 2 tables. Just move the Profile columns into User table (they have the exact same functional dependencies). If you must maintain both tables drop the profile_id FK from users and create a unique constraint on the user_id FK in profile. – Belayer Mar 03 '20 at 17:58

0 Answers0