评论功能实现

说一下为什么要做这个,这段时间做毕设需要这个功能,然后今天搞了一天,我不太擅长搞后端,看了好久,也算是记录一下自己的学习,毕竟答辩的时候还需要呢。

先上效果图(我看别人博客老是没有效果就很烦)

说一下大致思路(实现两级):(判题系统)

  1. 前端通过当前问题的id去请求后端,然后后端查询关于此题目的相关评论集合返回给前端
  2. 添加评论,这个通过当前题目的id,和评论id,当前用户的id,如果是二级评论则要targetId即子级评论。
  3. 在添加的时候要想明白,一级评论,二级评论之间关系,怎么去区分,我做的时候他们的请求参数不一样,二级评论的参数要加上 parentId和targetId这样才能形成嵌套关系,从遍历获取即可。(补充这里的还应该返回每条评论的user对象,用于获取用户头像,用户名等)

数据库设计:

CREATE TABLE `comment` (
  `id` bigint NOT NULL COMMENT '评论id',
  `content` varchar(255) NOT NULL COMMENT '评论内容',
  `questionId` bigint NOT NULL COMMENT '题目id',
  `userId` bigint NOT NULL COMMENT '评论人id',
  `userAvatar` varchar(1024) DEFAULT NULL COMMENT '用户头像',
  `userName` varchar(25) DEFAULT NULL COMMENT '用户昵称',
  `parentId` bigint DEFAULT NULL COMMENT '评论父级id',
  `targetId` bigint DEFAULT NULL COMMENT '回复目标对象id',
  `createTime` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
  `isDelete` tinyint unsigned NOT NULL DEFAULT '0' COMMENT '是否删除 0未删除 1删除',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

JavaBean:

/**
     * 评论id
     */
    @TableId
    private Long id;

    /**
     * 评论内容
     */
    private String content;

    /**
     * 题目id
     */
    private Long questionId;

    /**
     * 评论人id
     */
    private Long userId;

    /**
     * 用户头像
     */
    private String userAvatar;

    /**
     * 用户昵称
     */
    private String userName;

    /**
     * 评论父级id
     */
    private Long parentId;

    /**
     * 回复目标对象id
     */
    private Long targetId;

    /**
     * 创建时间
     */
    private Date createTime;

    /**
     * 是否删除 0未删除 1删除
     */
    private Integer isDelete;
    /**
     * 子评论
     * */
    private List<Comment> children;

添加实现:

    @PostMapping("/add")
    public BaseResponse<Long> addComment(@RequestBody CommentAddRequest commentAddRequest, HttpServletRequest request) {
        if (commentAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Comment comment = new Comment();
        BeanUtils.copyProperties(commentAddRequest, comment);
        User loginUser = userService.getLoginUser(request);
        comment.setUserId(loginUser.getId());
        comment.setCreateTime(new Date());
        boolean result = commentService.save(comment);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        Long newCid = comment.getId();
        return ResultUtils.success(newCid);
    }

条件查询实现:

 /**
     * 根据 id 获取
     *
     * @param id
     * @return 根据id获取当前题目下的评所有评论
     */
    @GetMapping("/get")
    public BaseResponse<List<Comment>> getCommentByQuestionId(Long id, HttpServletRequest request) {

        return ResultUtils.success(commentService.getComment(id, request));
    }

评论如何返回给前端最重要的就是这个方法:

/**
     * 构建评论树
     * @param list
     * @return
     */
    public static List<Comment> processComments(List<Comment> list) {
        Map<Long, Comment> map = new HashMap<>();   // (id, Comment)
        List<Comment> result = new ArrayList<>();
        // 将所有根评论加入 map
        for(Comment comment : list) {
            if(comment.getParentId() == null)
                result.add(comment);
            map.put(comment.getId(), comment);
        }
        // 子评论加入到父评论的 children 中
        for(Comment comment : list) {
            Long id = comment.getParentId();
            if(id != null) {   // 当前评论为子评论
                Comment p = map.get(id);
                if(p.getChildren() == null)    // children 为空,则创建
                    p.setChildren(new ArrayList<>());
                p.getChildren().add(comment);
            }
        }
        return result;
    }

返回数据格式 :

{
      "id": "1774656313639944193",
      "content": "gvyfasgfgsayugfhas",
      "questionId": "1",
      "userId": "1771795740782833666",
      "userAvatar": null,
      "userName": "",
      "parentId": null,
      "targetId": null,
      "createTime": "2024-04-01T07:28:10.000+00:00",
      "isDelete": 0,
      "children": [
        {
          "id": "1774797768555577345",
          "content": " 就这难度",
          "questionId": "1",
          "userId": "1771924522776735746",
          "userAvatar": null,
          "userName": null,
          "parentId": "1774656313639944193",
          "targetId": null,
          "createTime": "2024-04-01T13:55:37.000+00:00",
          "isDelete": 0,
          "children": null
        }
      ]
    }

前端调用接口通过v-for遍历

如果children不为null 嵌套遍历

我使用的是arco-design组件库Arco Design Vue

然后就没有什么较难的啦

时间转换使用的是moment().format("LLL");

参考:Vue+SpringBoot实现评论功能_springboot vue 评论区-CSDN博客

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在Django实现评论功能,一般需要以下步骤: 1. 创建Comment模型并与其他模型进行关联,例如某篇文章的评论。 2. 编CommentForm表单,用于接收用户提交的评论内容。 3. 在视图函数处理表单数据,验证并保存评论到数据库。 4. 在模板展示评论列表和评论表单。 下面是一个简单的实现过程: 1. 创建Comment模型 ```python from django.db import models from django.contrib.auth.models import User class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() created_time = models.DateTimeField(auto_now_add=True) article = models.ForeignKey('Article', on_delete=models.CASCADE) def __str__(self): return self.content ``` 2. 编CommentForm表单 ```python from django import forms class CommentForm(forms.Form): content = forms.CharField(widget=forms.Textarea) ``` 3. 编视图函数 ```python from django.shortcuts import render, get_object_or_404, redirect from .models import Article, Comment from .forms import CommentForm def article_detail(request, pk): article = get_object_or_404(Article, pk=pk) comments = Comment.objects.filter(article=article) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.user = request.user comment.article = article comment.save() return redirect('article_detail', pk=article.pk) else: form = CommentForm() return render(request, 'article_detail.html', {'article': article, 'comments': comments, 'form': form}) ``` 4. 在模板展示评论列表和评论表单 ```html {% extends 'base.html' %} {% block content %} <h1>{{ article.title }}</h1> <p>{{ article.content }}</p> <h2>Comments</h2> <ul> {% for comment in comments %} <li>{{ comment.content }}</li> {% empty %} <li>No comments yet.</li> {% endfor %} </ul> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% endblock %} ``` 以上是一个简单的评论功能实现过程,需要根据具体情况进行调整和完善。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值