Postgres enum in typeorm

前端 未结 4 1159
南笙
南笙 2021-02-18 18:49

In typeorm, how can I create a postgres enum type Gender as in this raw query

CREATE TYPE public.Gender AS ENUM (
    \'male\', \'female\'
);
ALTER TABL         


        
4条回答
  •  情书的邮戳
    2021-02-18 19:21

    EDIT: This answer is still valid but a bit outdated as 0.1.0 alpha versions of TypeORM support enums for both PostgreSQL and MySQL.


    PostgreSQL has a built in enum type, but unfortunately TypeORM currently only supports it for MySQL.

    However, you could achieve a similar result with an int-type enum by using the @Column type as int and using the enum for your field type.

    enum Gender {
      Male,
      Female,
      Other
    }
    
    @Entity()
    export class Person {
        @Column('int')
        gender: Gender
    }
    

    (This approach lets you use the @IsEnum decorator from class-validator to validate the input if needed)

    You could also use string enums (available on TypeScript 2.4, check Typescript `enum` from JSON string for older versions) and if that is the case just change the data type to string instead.

    enum Gender {
      Male = 'male',
      Female = 'female',
      Other = 'other'
    }
    
    @Entity()
    export class Person {
        @Column('text')
        gender: Gender
    }
    

提交回复
热议问题