后端写评论功能(递归)

目录

1.需求讲解

2.建表

3.实体类

3.代码

4.结果集


1.需求讲解

在发表评论的时候,我们需要点击发表内容的首页,然后发表情况。这里有两种情况

1.对当前发表内容的评论

2.回复评论内容

这里提供一个解决思路

评论区可以看成一个树形的结构。如果在一张表进行时,我们需要记录父级评论的id,评论首次显示为父级评论id为0的评论,并在该实体类中添加对应的子节点并返回。

2.建表

create table tb_blog_comments
(
    id          bigint unsigned auto_increment comment '主键'
        primary key,
    user_id     bigint unsigned                     not null comment '用户id',
    blog_id     bigint unsigned                     not null comment '点评id',
    parent_id   bigint unsigned                     not null comment '关联的1级评论id,如果是一级评论,则值为0',
    content     varchar(255)                        not null comment '回复的内容',
    liked       int unsigned                        null comment '点赞数',
    status      tinyint   default 0                 null comment '0表示正常,1被举报,2禁止',
    create_time timestamp default CURRENT_TIMESTAMP not null comment '创建时间',
    update_time timestamp default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
    is_deleted  tinyint   default 0                 not null comment '删除标记(0:可用 1:删除)'
)
    comment '点评评论表';

3.实体类

@Getter
@Setter
@TableName("tb_blog_comments")
@ApiModel(value = "BlogComments对象", description = "评论表评论")
public class BlogComments implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty("主键")
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    @ApiModelProperty("用户id")
    @TableField("user_id")
    private Long userId;

    @ApiModelProperty("点评id")
    @TableField("blog_id")
    private Long blogId;

    @ApiModelProperty("关联的1级评论id,如果是一级评论,则值为0")
    @TableField("parent_id")
    private Long parentId;

    @ApiModelProperty("回复的内容")
    @TableField("content")
    private String content;

    @ApiModelProperty("点赞数")
    @TableField("liked")
    private Integer liked;

    @ApiModelProperty("状态,0:正常,1:被举报,2:禁止查看")
    @TableField("`status`")
    private Integer status;

    @ApiModelProperty("创建时间")
    @TableField("create_time")
    private LocalDateTime createTime;

    @ApiModelProperty("更新时间")
    @TableField("update_time")
    private LocalDateTime updateTime;

    @ApiModelProperty("删除标记(0:可用 1:删除)")
    @TableField("is_deleted")
    @TableLogic
    private Integer isDeleted;

    /*
    * 下级表
    * */
    @TableField(exist = false)
    private List<BlogComments> children;
}

3.代码

    /*
     * 递归方法创建目录,寻找子结点
     * */
    private BlogComments findChildren(BlogComments blogComment, List<BlogComments> treeNodes) {
        blogComment.setChildren(new ArrayList<BlogComments>());
        for (BlogComments tn : treeNodes) {
            if (blogComment.getId().longValue() == tn.getParentId().longValue()) {
                if (blogComment.getChildren() == null) {
                    blogComment.setChildren(new ArrayList<>());
                } else {
                    blogComment.getChildren().add(findChildren(tn, treeNodes));
                }
            }
        }
        return blogComment;
    }
    /*
    * 
    * 合并子结点
    * */
    private List queryAllComments(List<BlogComments> blogComments) {
        blogComments.stream().forEach(a -> {
            findChildren(a, blogComments);
        });
        List<BlogComments> comments = blogComments.stream().filter(bc -> bc.getParentId()==0L).collect(Collectors.toList());
        return comments;
    }

   /*
   * 查询评论表内容
   * */
    @Override
    public Result commentByBlogId(String blogId) {
        QueryWrapper<BlogComments> wrapper = new QueryWrapper<>();
        wrapper.eq("blog_id", blogId);
        BlogCommentsMapper baseMapper = this.getBaseMapper();
        List<BlogComments> blogComments = baseMapper.selectList(wrapper);
        return Result.ok(queryAllComments(blogComments));
    }

4.结果集

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的评论模块的后端代码实现: 首先,我们需要一个表来存储评论信息,可以创建一个名为 `comments` 的表,包含以下字段: - `id`:评论的唯一标识符,自增长整数类型。 - `user_id`:评论者的用户 ID。 - `post_id`:被评论的文章或帖子的 ID。 - `content`:评论的内容。 - `created_at`:评论的创建时间。 接下来,我们创建一个 `Comment` 模型来映射 `comments` 表: ```python from sqlalchemy import Column, Integer, String, DateTime from database import Base class Comment(Base): __tablename__ = 'comments' id = Column(Integer, primary_key=True, autoincrement=True) user_id = Column(Integer) post_id = Column(Integer) content = Column(String) created_at = Column(DateTime) ``` 在上述代码中,我们使用 SQLAlchemy 库创建了一个名为 `Comment` 的模型,它包含了与 `comments` 表对应的字段。 接下来,我们需要创建一些路由来处理评论相关的请求。例如,当用户想要发表一条评论时,我们可以创建一个 `POST` 请求的路由,如下所示: ```python from datetime import datetime from flask import Flask, request, jsonify from models import Comment from database import db_session app = Flask(__name__) @app.route('/comments', methods=['POST']) def create_comment(): user_id = request.json['user_id'] post_id = request.json['post_id'] content = request.json['content'] created_at = datetime.now() comment = Comment(user_id=user_id, post_id=post_id, content=content, created_at=created_at) db_session.add(comment) db_session.commit() return jsonify({'message': 'Comment created successfully.'}), 201 ``` 在上述代码中,我们首先从请求中获取评论相关的信息,包括评论者的用户 ID、被评论的文章或帖子的 ID、评论的内容和评论的创建时间。接下来,我们创建一个 `Comment` 对象,并将其添加到数据库中。 当用户想要获取某篇文章或帖子的所有评论时,我们可以创建一个 `GET` 请求的路由,如下所示: ```python @app.route('/comments/<int:post_id>', methods=['GET']) def get_comments(post_id): comments = Comment.query.filter_by(post_id=post_id).all() return jsonify({'comments': [comment.to_dict() for comment in comments]}), 200 ``` 在上述代码中,我们首先从请求中获取被评论的文章或帖子的 ID,然后使用 SQLAlchemy 查询所有与该文章或帖子相关的评论信息。最后,我们将查询结果转换为 JSON 格式并返回。 以上就是一个简单的评论模块的后端代码实现。当然,实际的代码可能会更加复杂,例如需要进行身份验证、防止恶意评论等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值