Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

nestjs - TypeORM - table inheritance using enum discriminator

Trying to use an enum to discriminate the child entities:

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
}

but I am running into an error:

[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/[email protected]/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

If I use a default value then I get the error

QueryFailedError: column "action_category" of relation "action" already exists
question from:https://stackoverflow.com/questions/65917455/typeorm-table-inheritance-using-enum-discriminator

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

So I was able to circumvent this issue by specifying the column name in the TableInheritance decoration:

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

this worked fine when leaving the @Column in the entity:

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...