首页 > 解决方案 > TypeORM - 使用枚举鉴别器的表继承

问题描述

尝试使用枚举来区分子实体:

export enum ActionCategory {
  USER = 'user',
  POSITION = 'position',
  NOTE = 'note',
  EMAIL = 'email',
}

@Index('action_pkey', ['id'], { unique: true })
@Entity()
@TableInheritance({
  column: { type: 'enum', enum: ActionCategory, name: 'category' },
})
export class Action {
  @PrimaryGeneratedColumn({
    name: 'action_id',
    type: 'bigint',
  })
  readonly id: number

  @Column({
    name: 'category',
    type: 'enum',
    enum: ActionCategory,
    default: ActionCategory.USER
  })
  readonly category: ActionCategory
}

但我遇到了一个错误:

[Nest] 52222   - 27/01/2021, 10:30:25   [TypeOrmModule] Unable to connect to the database. Retrying (2)... +1ms
QueryFailedError: column "action_category" contains null values
    at new QueryFailedError (/Users/rai/dev/lexstep/lexstep-nest/node_modules/.pnpm/typeorm@0.2.29/node_modules/typeorm/error/QueryFailedError.js:11:28)
I can avoid this issue by changing the name of one of the columns (either the @TableInheritance 'action_category' or the @Column 'action_category' but this results in an extra column being created

如果我使用默认值,那么我会收到错误

QueryFailedError: column "action_category" of relation "action" already exists

标签: nestjstypeorm

解决方案


TableInheritance所以我可以通过在装饰中指定列名来规避这个问题:

@TableInheritance({
  column: 'category',
})

离开@Column实体时,这工作正常:

export class Action extends Timestamped {
  @PrimaryGeneratedColumn('uuid', {
    name: 'action_id',
  })
  readonly id: string

  @Column({
    name: 'action_category',
    type: 'enum',
    default: ActionCategory.SYSTEM,
    enum: ActionCategory,
  })
  readonly category: ActionCategory
}

推荐阅读