41
loading...
This website collects cookies to deliver better user experience
model Post {
...
comments Comment[]
}
model Comment {
id Int @id @default(autoincrement())
text String
post Post @relation(fields: [postId], references: [id], onDelete: NoAction, onUpdate: Cascade)
postId Int
}
@relation
)post Post @relation(fields: [postId], references: [id], onDelete: NoAction, onUpdate: Cascade)
postId
related to the field id
in Post
entity. In this way you described the relation between Post and Comment entities. It's also possibile to describe what to do when a foreign key is deleted or updated using the keyword onDelete
and onUpdate
. This two commands could have 5 possibile values:comments Comment[]
model Comment {
...
post Post? @relation(fields: [postId], references: [id])
postId Int?
...
}
?
character, you should indicate to Prisma that the field can be null.model Post {
id Int @id @default(autoincrement())
title String
content String
published Boolean
comments Comment[]
authors AuthorsOnPost[]
}
model Author {
id Int @id @default(autoincrement())
firstName String
lastName String
comments Comment[]
posts AuthorsOnPost[]
}
model AuthorsOnPost {
author Author @relation(fields: [authorId], references: [id])
authorId Int
post Post @relation(fields: [postId], references: [id])
postId Int
@@id([authorId, postId])
}
authorId
and postId
.
authorId
is a foreign key related to the Author Entity whereas postId
is a foreign key related to the Post Entity, I think if you understood the previous paragraph, you don't have any problem to understand this. Using the @@id
you indicated to prisma that the AuthorsOnPost had a primary key composed by this two fields, so you can have the same author and the same post only once. By doing that, you have created a relation N-N between Authors and Posts, so in your database now, you can have a Post with multiple Authors and an Author can contribute to multiple Posts.
The last two steps instead allow you to have the collection of Authors related to a Post and viceversa.model Post {
...
author Author @relation(fields: [authorId], references: [id])
authorId Int
}
model Author {
.....
post Post?
}
prisma-erd-generator
yarn add -D prisma-erd-generator
prisma/schema.prisma
with the following code
generator client {
provider = "prisma-client-js"
}
generator erd {
provider = "prisma-erd-generator"
}
...
npx prisma generate
, Prisma generates for you also a file prisma/ERD.svg
where you can see your ER Diagram.npx prisma generate
npx prisma db push