乐闻世界logo
搜索文章和话题

How to add an enum array in a TypeOrm entity?

1个答案

1

In TypeORM, to add an enum array to an entity, we can utilize the enum keyword along with the array: true property. This ensures that the field is properly defined as an array of enum values in the database. Below is a step-by-step guide and example:

Step 1: Define the Enumeration Type

First, we need to define an enumeration type. An enumeration type is a special data type that contains a predefined set of finite values which are logically related. For example, if we want to store user roles, we can define it as:

typescript
export enum UserRole { ADMIN = "admin", EDITOR = "editor", VIEWER = "viewer" }

Step 2: Use the Enum Array in the Entity

Next, in the entity definition, we use this enumeration type and specify the field as an enum array using the @Column decorator. We set type: 'enum' and enum: UserRole to define the field's type, and set array: true to indicate it is an array type.

typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"; import { UserRole } from "./UserRole"; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column("varchar", { length: 255 }) name: string; @Column({ type: "enum", enum: UserRole, array: true }) roles: UserRole[]; }

In this example, the roles field is defined as an array of UserRole enum values, meaning each element must conform to one of the values defined in the UserRole enum.

Notes

  • Ensure the database supports enum array types. For instance, PostgreSQL supports this type, but it may not be supported in other databases.
  • During database migrations, TypeORM should correctly handle the creation of enum arrays.
  • When handling data queries or updates, ensure that the values passed to the enum array conform to the enum definition.

This method is highly useful for managing users with multiple roles or attributes, and it ensures data consistency and validation in a simple and efficient manner.

2024年7月31日 00:42 回复

你的答案