Prisma 模型设计
model Comment {
id String @id @default(cuid())
blog_post_id String? // 关联博客文章 (顶级评论)
parent_comment_id String? // 关联父评论 (嵌套评论)
user_id String // 评论人 ID
content String @db.Text
likes Int @default(0) // 点赞数
status String @default("visible") // "visible" | "hidden"
created_at DateTime @default(now())
updated_at DateTime @updatedAt
// 关系定义
blog_post BlogPost? @relation(fields: [blog_post_id], references: [id], onDelete: Cascade)
parent_comment Comment? @relation("CommentToComment", fields: [parent_comment_id], references: [id], onDelete: Cascade)
child_comments Comment[] @relation("CommentToComment")
user User @relation(fields: [user_id], references: [id], onDelete: Cascade)
@@map("comments")
}
Prisma 查询示例
获取文章下的评论(带嵌套评论)
import { prisma } from '@/lib/prisma'
export async function getCommentsByPost(postId: string) {
const comments = await prisma.comment.findMany({
where: {
blog_post_id: postId,
parent_comment_id: null // 仅获取顶级评论
},
include: {
child_comments: {
include: {
child_comments: true // 深度嵌套
}
}
},
orderBy: { created_at: 'asc' } // 按时间升序
})
return comments
}
添加评论
对博客文章发表评论
import { prisma } from '@/lib/prisma'
export async function addCommentToPost(postId: string, userId: string, content: string) {
return await prisma.comment.create({
data: {
blog_post_id: postId,
user_id: userId,
content
}
})
}
对评论进行回复
import { prisma } from '@/lib/prisma'
export async function replyToComment(parentCommentId: string, userId: string, content: string) {
return await prisma.comment.create({
data: {
parent_comment_id: parentCommentId,
user_id: userId,
content
}
})
}
点赞评论
import { prisma } from '@/lib/prisma'
export async function likeComment(commentId: string) {
await prisma.comment.update({
where: { id: commentId },
data: { likes: { increment: 1 } }
})
}
数据示例
[
{
"id": "cmt_001",
"content": "这篇文章写得很好!",
"likes": 10,
"child_comments": [
{
"id": "cmt_002",
"content": "我也觉得很棒!",
"likes": 5,
"child_comments": [
{
"id": "cmt_003",
"content": "确实如此!",
"likes": 3
}
]
}
]
}
]
TODO 后续优化功能
✅ 评论排序(按点赞数、时间等)
✅ 评论@用户(提醒用户有新回复)
✅ 评论编辑/删除(用户可以修改或删除自己的评论)
✅ 评论通知系统(提示用户有新评论或回复)
✅ 折叠评论(针对大量嵌套评论时的 UI 优化)