Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query Enum type on Prisma

I am trying to run a query on a simple prisma entity User. Model:

model User {
  id           Int              @id @default(autoincrement())
  name         String?
  email        String           @unique
  role         Role             @default(USER)
}

Entity User includes a prop called Role with a type of enum. Role enum:

enum Role {
  USER
  ADMIN
}

Except doing it in raw SQL query, how is this possible to do with Prisma where API:

const whereNameIs = await prisma.user.findMany({
  name: 'Rich',
  role: ?
})

Any custom enum type written in TS or conversion won't match. Is there any workaround in typescript for this?

like image 818
Jora Avatar asked Dec 02 '25 17:12

Jora


1 Answers

Prisma library gives named export of any enum types you have defined in the schema file:

import { Role } from '@prisma/client'

app.get('users', async (req, res) => {
  const users = await prisma.user.findMany({
    name: 'Rich',
    role: Role.ADMIN
  });
});

if you receive the value dynamically, say through a query string, then it would be as follows:

const { role } = req.query;

const users = await prisma.user.findMany({
  name: 'Rich',
  role: Role[role as keyof typeof Role]
});
like image 108
Jora Avatar answered Dec 05 '25 10:12

Jora



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!