Prisma client enum

Prisma Client Enum

Prisma Client Enum is a feature provided by Prisma, which is an Object-Relational Mapping (ORM) tool used for database access. Enums in Prisma define a set of possible values that a field can have. This helps in ensuring data consistency and providing easy-to-understand options for the users of your application.

Let us consider an example to understand the usage of Prisma Client Enum. Suppose we have a database table named “User” with a field called “role”. The “role” field can have one of the three values: “ADMIN”, “USER”, or “GUEST”. We can define this field as an enum in Prisma.


    model User {
      id    Int    @id @default(autoincrement())
      name  String
      role  Role
    }

    enum Role {
      ADMIN
      USER
      GUEST
    }
  

In the example above, we have defined an enum named “Role” with three possible values: “ADMIN”, “USER”, and “GUEST”. The “role” field in the “User” model is of type “Role”, and it can only have one of these three values.

We can now use Prisma Client to interact with the database and perform operations like creating a new user, updating the role of a user, or fetching users with a specific role. Here’s an example of using Prisma Client with enums:


    const user = await prisma.user.create({
      data: {
        name: "John Doe",
        role: "ADMIN"
      }
    });
  

In the above code snippet, we are creating a new user with the name “John Doe” and assigning the role “ADMIN” to the user. Prisma Client ensures that only the allowed enum values are used for the “role” field.

Enums in Prisma Client provide a convenient way to define and enforce a set of allowed values for a field in your database. They help in maintaining data integrity and enable easier data manipulation in your application.

Leave a comment