简体   繁体   中英

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM