typeorm 中的 Postgres 枚举 [英] Postgres enum in typeorm
问题描述
在 typeorm 中,如何创建 postgres 枚举类型 Gender 就像在这个原始查询中一样
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 TABLE public.person ALTER COLUMN gender TYPE public.gender USING gender::gender;
并在实体类中使用它?
我试过了
@Entity()
export class Person {
@Column('enum')
gender: 'male' | 'female'
}
但显然这不是正确的方法,因为我收到错误消息type enum不存在".
but obviously this isn't the right way, since I got the error message "type enum does not exist".
我也不想使用 typescript 枚举,因为它会在数据库中给我一堆 0 和 1.
I don't want to use typescript enum either, since it will give me a bunch of 0s and 1s in the database.
推荐答案
这个答案仍然有效,但作为 TypeORM 的 0.1.0
alpha 版本有点过时了支持 PostgreSQL 和 MySQL 的枚举.
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
有一个内置的枚举类型,但不幸的是 TypeORM
目前 仅支持 MySQL.
PostgreSQL
has a built in enum type, but unfortunately TypeORM
currently only supports it for MySQL.
但是,您可以通过将 @Column
类型用作 int
并将枚举用于您的字段类型来使用 int 类型枚举获得类似的结果.>
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
}
(这种方法允许您使用 @IsEnum
装饰器从class-validator 用于在需要时验证输入)
(This approach lets you use the @IsEnum
decorator from class-validator to validate the input if needed)
您也可以使用字符串枚举(在 TypeScript 2.4 上可用,请查看 Typescript `enum` from JSON string 对于旧版本),如果是这种情况,只需将数据类型更改为 string
.
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
}
这篇关于typeorm 中的 Postgres 枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!