Prisma 实现多层嵌套评论系统:从模型设计到完整实现

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 优化)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值