How to self-reference in TypeOrm

Viewed 289

I am trying to create a user entity which is supposed to have

import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn } from 'typeorm';

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

  @Column({unique: true})
  username: string;

  @Column()
  password: string;

  @CreateDateColumn()
  create_at: Date;

  @UpdateDateColumn()
  last_update_at: Date;

  //this is where I need help
  created_by: (this should be the ID of itself)
 
}

I am supposed to have the created by column as a self-referencing foreign key, but I can't figure it out. It keeps being either null or not showing at all when I tried. Complete database newbie here. I don't understand the relation doc quite well yet.

1 Answers

I suppose it should be like this:

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

  @Column({unique: true})
  username: string;

  @Column()
  password: string;

  @CreateDateColumn()
  create_at: Date;

  @UpdateDateColumn()
  last_update_at: Date;

  @OneToOne(() => User)
  @JoinColumn()
  createdBy: User;
}
Related