Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i create multiple schema in prisma for each model?

Tags:

schema

prisma

This is a default structure of prisma schema...

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}

model User {
  id Int  @id @default(autoincrement())
  username String @unique @db.VarChar(255)
  role UserRole @default(admin)
  posts Post[]
}

model Post {
  id Int @id @default(autoincrement())
  title String 
  post String @db.VarChar(500)
  created_at DateTime @default(now())
  updated_at DateTime @updatedAt
  user_id Int
  user User @relation(fields: [user_id], references: [id])
}

//custom enums
enum UserRole {
  client
  admin
}

I want to create multiple schema for each models. User schema for user model, Post schema for post model. Like we use models in mongoose. Is it possible in Prisma ORM?

like image 707
Farhaan Mahbub Avatar asked Oct 20 '25 17:10

Farhaan Mahbub


2 Answers

Since Prisma hasn't introduced any solution for this matter yet, used this awesome package Prismix and solved the issue. Thanks, everyone!

like image 126
Farhaan Mahbub Avatar answered Oct 25 '25 19:10

Farhaan Mahbub


Prisma multiSchema is now supported as a preview feature.

See here https://www.prisma.io/docs/guides/database/multi-schema

It was introduced in version 4.3.0 https://github.com/prisma/prisma/issues/1122#issuecomment-1231773471

As the docs say you would add the preview feature...

generator client {
  provider = "prisma-client-js"
  previewFeatures = ["multiSchema"]
}

Then in your datasource you note the schemas...

datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
  schemas  = ["User", "Post"]
}

And finally in each model you add the @@schema attribute...

model User {
  id Int  @id @default(autoincrement())
  username String @unique @db.VarChar(255)
  role UserRole @default(admin)
  posts Post[]

  @@schema("User")
}

model Post {
  id Int @id @default(autoincrement())
  title String 
  post String @db.VarChar(500)
  created_at DateTime @default(now())
  updated_at DateTime @updatedAt
  user_id Int
  user User @relation(fields: [user_id], references: [id])

  @@schema("Post")
}

Note:

It might not be possible to do cross schema foreign keys. I saw it mentioned somewhere, but I can't find it now.

like image 40
shmuels Avatar answered Oct 25 '25 21:10

shmuels



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!