Complete the code to define a one-to-many relation in Prisma schema.
model User {
id Int @id @default(autoincrement())
posts Post[] [1]
}
model Post {
id Int @id @default(autoincrement())
userId Int
user User @relation(fields: [userId], references: [id])
}The @relation("UserPosts") decorator names the relation and connects the posts field in User to the user field in Post, establishing a one-to-many relation.
Complete the code to fetch a user with their posts using Prisma Client.
const userWithPosts = await prisma.user.findUnique({
where: { id: userId },
[1]: { posts: true }
});The include option tells Prisma Client to fetch related records, here the posts of the user.
Fix the error in the Prisma schema relation definition.
model Profile {
id Int @id @default(autoincrement())
userId Int @unique
user User [1]
}
model User {
id Int @id @default(autoincrement())
profile Profile?
}The @relation(fields: [userId], references: [id]) decorator correctly defines the foreign key and references for the one-to-one relation.
Fill both blanks to define a many-to-many relation in Prisma schema.
model Student {
id Int @id @default(autoincrement())
courses Course[] [1]
}
model Course {
id Int @id @default(autoincrement())
students Student[] [2]
}Both sides of a many-to-many relation use the same @relation name to link the two models.
Fill all three blanks to create a nested create operation with relations in Prisma Client.
const newUser = await prisma.user.create({
data: {
name: 'Alice',
posts: {
[1]: [
{ title: 'First Post', content: 'Hello' },
{ title: 'Second Post', content: 'World' }
]
},
profile: {
[2]: {
bio: 'Developer'
}
},
[3]: true
}
});Use create to nest creation of related records, and include to fetch related data in the result.