Перейти к содержимому

21. Реальный проект: Blog API

В этом уроке мы рассмотрим полноценную схему блог-платформы и научимся строить сложные запросы для реальных задач. Приложение включает пользователей, посты, комментарии, теги и категории.

model User {
id Int @id @default(autoincrement())
email String @unique
name String
bio String?
avatar String?
role Role @default(USER)
posts Post[]
comments Comment[]
createdAt DateTime @default(now())
@@index([email])
}
model Post {
id Int @id @default(autoincrement())
title String
slug String @unique
content String
published Boolean @default(false)
viewCount Int @default(0)
author User @relation(fields: [authorId], references: [id])
authorId Int
category Category @relation(fields: [categoryId], references: [id])
categoryId Int
tags Tag[]
comments Comment[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([authorId])
@@index([categoryId])
@@index([slug])
}
model Comment {
id Int @id @default(autoincrement())
body String
author User @relation(fields: [authorId], references: [id])
authorId Int
post Post @relation(fields: [postId], references: [id])
postId Int
createdAt DateTime @default(now())
}
model Tag {
id Int @id @default(autoincrement())
name String @unique
posts Post[]
}
model Category {
id Int @id @default(autoincrement())
name String @unique
posts Post[]
}
// Получить посты с авторами, тегами и количеством комментариев
const posts = await prisma.post.findMany({
where: { published: true },
include: {
author: { select: { name: true, avatar: true } },
tags: true,
category: true,
_count: { select: { comments: true } },
},
orderBy: { createdAt: 'desc' },
take: 10,
})