Representing a User with sub-roles

Hello, I'm trying to figure out the best way to represent this relationship. I know union types aren't possible in the schema but I can define them in the sdl. I'm not sure a union is what I want though, because it adds complexity to the queries. Essentially I have a user. I don't do a lot of business logic in my app with that user though, instead I use other models like "Staff" and "Customer". A user could be a staff OR a customer. During the user creation process I connect either the staff or customer model. However that leads to one being empty and my app having to probe whether a user is staff or customer. I'm currently doing something like this (reason being staff and customer are very different, so this scales better):
model User {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
email String @unique
hashedPassword String @default("")
salt String @default("")
firstName String
staff Staff?
customer Customer?
}
model User {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
email String @unique
hashedPassword String @default("")
salt String @default("")
firstName String
staff Staff?
customer Customer?
}
I've also explored another option where:
model User {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
email String @unique
hashedPassword String @default("")
salt String @default("")
firstName String
userType UserType
}

model UserType {
id Int @id @default(autoincrement())
staff Staff?
customer Customer?
}
model User {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
email String @unique
hashedPassword String @default("")
salt String @default("")
firstName String
userType UserType
}

model UserType {
id Int @id @default(autoincrement())
staff Staff?
customer Customer?
}
But I'm not sure what's best. I wish I could do something like:
userType Staff | Customer
userType Staff | Customer
What are best practices or recommendations to represent relationships like this?
1 Reply
citrinitas
citrinitas4mo ago
Nevermind, if anyone ever considers this the issue is that prisma doesn't support polymorphism. I ended up doing this in my user model: @@unique([staffId, customertId]) to ensure user can be only staff or customer. And then in my sdl: union RoleDetails = Staff | Customer union type. So that I can return it in the resolver properly: return { ...user, roleDetails: user.staff || user.customer }; Zenstack apparently supports this: https://zenstack.dev/docs/next/guides/polymorphism
Want results from more Discord servers?
Add your server