Allow for model inheritance, to reduce repetitive code.
typescript - Get base model types on client with Prisma and NextJS - Stack Overflow
Is there a way to create abstract models in prisma ORM?
Possibility to merge & extend prisma models ?
In short: No there is such thing as abstract models or inheritance in general implemented in Prisma as of now.
However there is an open Github issue proposal which describes how interfaces could be used for that kind of abstraction. https://github.com/prisma/prisma/issues/2506. Unfortunately there hasn't been made any real progress on the issue since 2020.
Thus people started to implement it by themselves.
A custom library called ZenStack built on top of Prisma offers abstract models. You can define .zmodel model files which are compiled to the normal prisma.schema.
An example from the ZenStack documentation:
abstract model Basic { id String @id createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } model User extends Basic { name String }The generated prisma file only contains one User model:
model User { id String @id createdAt DateTime @default(now()) updatedAt DateTime @updatedAt name String @id }
Prisma ORM does not have the concept of "abstract models" in the same way Django ORM does. In Django, an abstract model serves as a base class for other models but does not produce a database table of its own. Instead, its fields are added to the child models that inherit from it.
In Prisma, you can't define a model that is only used for inheritance purposes. However, there are certain approaches you can take to emulate abstract-like behavior:
Using Generators or Scripts:
You could set up a generator or a script to produce the final schema.prisma file by combining shared fields and model-specific fields. This is a more involved setup but can help maintain DRYness if you have a lot of shared fields.
Model Relations instead of Inheritance:
Consider if a relation between models might serve better than inheritance. For instance, if there's a shared set of attributes across multiple models, those attributes could be refactored into their own model, and a relation could be established.
model Profile {
id Int @id @default(autoincrement())
name String
email String @unique
user User? @relation(fields: [userId], references: [id])
userId Int?
admin Admin? @relation(fields: [adminId], references: [id])
adminId Int?
}
model User {
id Int @id @default(autoincrement())
profile Profile @relation(fields: [profileId], references: [id])
profileId Int
// ... other specific fields ...
}
model Admin {
id Int @id @default(autoincrement())
profile Profile @relation(fields: [profileId], references: [id])
profileId Int
// ... other specific fields ...
}
In this example, the Profile model holds fields common to both User and Admin.