With the rise of social media and content platforms, multi-level comment systems have become an important way for various platforms to interact with users and communities. It is relatively simple to implement a multi-level comment system on the front end, but it is relatively complicated to implement on the back end. This article will introduce how to use golang to implement multi-level comments.
Multi-level comments are actually a display of a tree structure, and each comment can be used as a node. Multi-level review systems can be implemented using tree and binary trees, the basic data structures of tree structures. In this article, we choose to use a tree-structured binary tree for implementation.
The node of the binary tree consists of two left and right child nodes. The left node is the first child node of the current node, and the right node is the second child node of the current node. Therefore, every time we add a comment, we only need to pay attention to the parent node of the current comment and its left and right child nodes.
In order to implement a multi-level comment system, the parent-child relationship of each comment needs to be stored in the database. In general, we can use two ways to store the tree structure:
In this article, we choose to use the second method, which is to use self-referential relationships in a single table.
The structure of the comment table (comment) is as follows:
CREATE TABLE `comment` ( `id` int(11) NOT NULL AUTO_INCREMENT, `parent_id` int(11) DEFAULT NULL COMMENT '父级评论id', `content` varchar(255) DEFAULT NULL COMMENT '评论内容', `created_at` datetime DEFAULT NULL COMMENT '创建时间', PRIMARY KEY (`id`), KEY `parent_id` (`parent_id`), CONSTRAINT `comment_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `comment` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='评论表'
In the above table structure, parent_id
represents the parent node id of the current comment, if the current comment is a first-level comment , then parent_id
is null. id
is the id of the current comment, content
is the comment content, and created_at
is the creation time.
First, you need to use the database/sql and mysql drivers in golang to link to the database:
dsn := "root:123456@tcp(127.0.0.1:3306)/test" db, err := sql.Open("mysql", dsn) if err != nil { fmt.Printf("mysql connect error %s", err.Error()) return }
When inserting a comment, you need to determine whether the current comment is processed as a parent node or a child node.
If the current comment is used as a parent node, it is inserted directly into the database. If the current comment is a child node, the right node of the parent node needs to be updated.
// 添加评论 func AddComment(comment Comment) error { if comment.ParentID == 0 { _, err := db.Exec("INSERT INTO comment(parent_id, content, created_at) VALUES(?, ?, ?)", nil, comment.Content, comment.CreatedAt) if err != nil { return err } } else { var rightNode *int err := db.QueryRow("SELECT right_node FROM comment WHERE id = ?", comment.ParentID).Scan(&rightNode) if err != nil { return err } tx, err := db.Begin() if err != nil { return err } // 更新右节点 _, err = tx.Exec("UPDATE comment SET right_node = right_node + 2 WHERE right_node > ?", rightNode) if err != nil { tx.Rollback() return err } _, err = tx.Exec("UPDATE comment SET left_node = left_node + 2 WHERE left_node > ?", rightNode) if err != nil { tx.Rollback() return err } _, err = tx.Exec("INSERT INTO comment(parent_id, left_node, right_node, content, created_at) VALUES(?, ?, ?, ?, ?)", comment.ParentID, rightNode, rightNode+1, comment.Content, comment.CreatedAt) if err != nil { tx.Rollback() return err } tx.Commit() } return nil }
When querying comments, you need to sort the nodes in left and right order to obtain a tree-structured comment list. When querying comments, since the left and right nodes need to be used for sorting, the left and right node columns need to be added to the query conditions. In addition, you also need to use a level field to indicate which level of node the current node is to facilitate front-end display.
type Comment struct { ID int `json:"id"` ParentID int `json:"parent_id"` Content string `json:"content"` LeftNode int `json:"left_node"` RightNode int `json:"right_node"` Level int `json:"level"` CreatedAt string `json:"created_at"` } // 获取评论列表 func GetComments() ([]Comment, error) { rows, err := db.Query("SELECT id, parent_id, content, created_at, left_node, right_node, (COUNT (parent.id) -1) AS level FROM comment AS node, comment AS parent WHERE node.left_node BETWEEN parent.left_node AND parent.right_node GROUP BY node.id ORDER BY left_node") if err != nil { return nil, err } defer rows.Close() var comments []Comment for rows.Next() { var comment Comment err := rows.Scan(&comment.ID, &comment.ParentID, &comment.Content, &comment.CreatedAt, &comment.LeftNode, &comment.RightNode, &comment.Level) if err != nil { return nil, err } comments = append(comments, comment) } return comments, nil }
When deleting a comment, you need to determine whether the current comment is a parent node or a child node. If it is a parent node, you need to delete the entire subtree.
// 删除评论 func DeleteComment(id int) error { tx, err := db.Begin() if err != nil { return err } var leftNode int var rightNode int err = tx.QueryRow("SELECT left_node, right_node FROM comment WHERE id = ?", id).Scan(&leftNode, &rightNode) if err != nil { tx.Rollback() return err } if leftNode == 1 && rightNode > 1 { // 删除子树 _, err = tx.Exec("DELETE FROM comment WHERE left_node >= ? AND right_node <= ?;", leftNode, rightNode) if err != nil { tx.Rollback() return err } err = tx.Commit() if err != nil { tx.Rollback() return err } } else { // 删除单个节点 _, err = tx.Exec("DELETE FROM comment WHERE id = ?", id) if err != nil { tx.Rollback() return err } err = tx.Commit() if err != nil { tx.Rollback() return err } } return nil }
Through the above code implementation, we can quickly build a fully functional multi-level comment system. Of course, this is only a basic implementation method. In actual scenarios, corresponding optimization and expansion need to be made according to specific needs.
The above is the detailed content of Golang implements multi-level comments. For more information, please follow other related articles on the PHP Chinese website!