1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【NestJS/TypeORM】STIを実装する

Last updated at Posted at 2021-02-15

環境

実装例

コード内のコメント部分が、STIに必要な実装です。

// 子テーブルの enum を定義する。
export enum ContentType {
  PHOTO = 'PHOTO',
  QUESTION = 'QUESTION',
}
@Entity()
// @TableInheritance を指定する。
// enum を指定する。
@TableInheritance({ column: { type: 'enum', enum: ContentType, name: 'type' } })
export class Content {
  @PrimaryGeneratedColumn()
  id: number;

  // type カラムを enum で明示的に定義する
  @Column({
    type: 'enum',
    enum: ContentType,
  })
  type: ContentType;
  
  @Column()
  title: string;
}
// @ChildEntity を指定する。
// 引数は、enum を使って明示的に指定する。
@ChildEntity(ContentType.PHOTO)
export class Photo extends Content {  
  @Column()
  size: string; 
}
// 同上
@ChildEntity(ContentType.QUESTION)
export class Question extends Content { 
  @Column()
  answersCount: number; 
}

参考ページ

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?