【问题标题】:TypeORM - table inheritance using enum discriminatorTypeORM - 使用枚举鉴别器的表继承
【发布时间】:2021-01-27 10:42:27
【问题描述】:

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

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

【问题讨论】:

    标签: nestjs typeorm


    【解决方案1】:

    所以我可以通过在 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
    }
    

    【讨论】:

      猜你喜欢
      • 2011-04-08
      • 1970-01-01
      • 2011-03-26
      • 2010-10-19
      相关资源
      最近更新 更多