Golang implements multi-level comments
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.
Implementation ideas
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.
Database Design
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:
- Use multi-table association
- Use self-referential relationships in a single table
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.
Code implementation
Link database
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 }
Insert comment
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 }
Query comments
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 }
Delete comments
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 }
Conclusion
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This article explains Go's package import mechanisms: named imports (e.g., import "fmt") and blank imports (e.g., import _ "fmt"). Named imports make package contents accessible, while blank imports only execute t

This article details efficient conversion of MySQL query results into Go struct slices. It emphasizes using database/sql's Scan method for optimal performance, avoiding manual parsing. Best practices for struct field mapping using db tags and robus

This article explains Beego's NewFlash() function for inter-page data transfer in web applications. It focuses on using NewFlash() to display temporary messages (success, error, warning) between controllers, leveraging the session mechanism. Limita

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

This article details efficient file writing in Go, comparing os.WriteFile (suitable for small files) with os.OpenFile and buffered writes (optimal for large files). It emphasizes robust error handling, using defer, and checking for specific errors.

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization
