Search code examples
node.jstypescripttypeorm

How to make a join of my first column TypeORM


I would like to create a verification email for my user. However, I don't see how I can make a join in my UserToken table with my user's id using typeorm.

Could someone please explain?

@Entity({name: "user_token"})
export class UserToken {
    @PrimaryColumn({name: "user_id"})
    @IsUUID()
    @IsNotEmpty()
    userId: UserId


    @Column({name: "token"})
    @IsString()
    @IsNotEmpty()
    token!: string
}
@Entity({name: "users"})
export class UserEntity {
    @PrimaryColumn({name: "id"})
    @IsUUID()
    @IsNotEmpty()
    id!: string
}

Solution

  • You may want to use the @ManyToOne() decorator in the UserToken entity, like so:

    @Entity({ name: 'user_token' })
    export class UserToken {
      @PrimaryColumn({ name: 'user_id' })
      @IsUUID()
      @IsNotEmpty()
      userId: UserId;
    
      @ManyToOne(() => UserEntity, user => user.userTokens, {
        onDelete: 'CASCADE',
      })
      @JoinColumn()
      user: User;
    
      @Column({ name: 'token' })
      @IsString()
      @IsNotEmpty()
      token!: string;
    }
    

    And then modify the User entity like so:

    @Entity({ name: 'users' })
    export class UserEntity {
      @PrimaryColumn({ name: 'id' })
      @IsUUID()
      @IsNotEmpty()
      id!: string;
    
      @OneToMany(() => UserToken, token => token.user)
      userTokens: UserToken[];
    }
    

    Since a user can have many tokens (incase one expires), you should have a one to many relationship.

    Visit the TypeORM documentation site to learn more about Relations: https://orkhan.gitbook.io/typeorm/docs/relations