Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k 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 Reply

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...