PrismaP
Prisma14mo ago
4 replies
Florian

Use foreign key as primary key

I've implemented multi-table inheritance following your guide: https://www.prisma.io/docs/orm/prisma-schema/data-model/table-inheritance#multi-table-inheritance-mti

My question: Is it possible to merge the foreign key and primary key on my child table? It's easier to query if the parent table (User) and child table (Admin) have the same id. But duplicating the ID is not great because it introduces room for mistakes.

I tried it earlier and got an error.

model User {
    id String @id // Clerk ID

    [... common user data]

    userType UserType?

    admin   Admin?
    teacher Teacher?
    student Student?
    parent  Parent?

    [...]
}

enum UserType {
    Admin
    Teacher
    Student
    Parent
}

model Admin {
    id String @id // Same Clerk ID as User -> easier to query

    // I would like to use the userId as the primary key and get rid of the duplicate Clerk ID.
    userId String @unique
    user   User   @relation(fields: [userId], references: [id], onDelete: Cascade)
}
Learn about the use cases and patterns for table inheritance in Prisma ORM that enable usage of union types or polymorphic structures in your application.
Table inheritance | Prisma Documentation
Was this page helpful?