Postgres enum in typeorm

前端 未结 4 1161
南笙
南笙 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:32

    Enum is now supported on TypeOrm for postgres

    By the docs

    enum column type is supported by postgres and mysql. There are various possible column definitions:

    Using typescript enums:

    export enum UserRole {
        ADMIN = "admin",
        EDITOR = "editor",
        GHOST = "ghost"
    }
    
    @Entity()
    export class User {
    
        @PrimaryGeneratedColumn()
        id: number;
    
        @Column({
            type: "enum",
            enum: UserRole,
            default: UserRole.GHOST
        })
        role: UserRole;
    
    }
    
    

    Using array with enum values:

    export type UserRoleType = "admin" | "editor" | "ghost",
    
    @Entity()
    export class User {
    
        @PrimaryGeneratedColumn()
        id: number;
    
        @Column({
            type: "enum",
            enum: ["admin", "editor", "ghost"],
            default: "ghost"
        })
        role: UserRoleType;
    }
    

提交回复
热议问题