Search code examples
nestjsentitytypeorm

how to create relationship between two entities with foreign key using typeorm


I need to create a relationship between two entities, I need that whenever I create a new user, a user account is created where the owner is the id of the created user.

Rules:

  1. When registering a new user must belong to a user account.
  2. Each user account must have an owner.
  3. I can have multiple users linked to one user account.

Below is the code I have today.

@Entity()
export class User extends BaseEntity { 
    @PrimaryGeneratedColumn('uuid')
    public id!: string;
    
    //cannot be null
    @ManyToOne(() => UserAccount, (obj) => obj.user)
    public userAccount: Relation<UserAccount>; 
}


@Entity()
export class UserAccount extends BaseEntity {
  @PrimaryGeneratedColumn('uuid')
  public id!: string;
  
  // must be unique and cannot be null
  @OneToOne(() => User, (user) => user.id)
  public owner: Relation<User>;

  @OneToMany(() => User, (obj) => obj.userAccount)
  public user: Relation<User>;
}

I tried the way it is above but it doesn't meet the rules described above.

How do I create the relationship between these two entities in a way that respects the rules described above?


Solution

  • The User table has OneToOne relation with UserAccount. Also, it has many linked accounts UserAccount[]. DOC

    @Entity()
    export class User extends BaseEntity {
        @PrimaryGeneratedColumn("uuid")
        public id!: string;
    
        @OneToOne(() => UserAccount, { nullable: false })
        @JoinColumn() // <-- creates relational column in user table
        public ownAccount!: UserAccount;
    
        @OneToMany(() => UserAccount, (userAccount) => userAccount.user)
        public linkedUserAccounts!: UserAccount[]; // <-- Array
    }
    
    @Entity()
    export class UserAccount extends BaseEntity {
        @PrimaryGeneratedColumn("uuid")
        public id!: string;
    
        @ManyToOne(() => User, (user) => user.linkedUserAccounts)
        @JoinColumn() // <-- creates relational column in UserAccount table
        public user!: User;
    }