diff --git a/internal/models.py b/internal/models.py index 4ddf81a..7cccda9 100644 --- a/internal/models.py +++ b/internal/models.py @@ -129,9 +129,12 @@ class Classtic(BaseModel): )] class Comment(BaseModel): + parent_id:Annotated[int,Field( + title="父级评论id", + description="父级评论允许为空" + )] blog_id:Annotated[int,Field( title="博客id", - default=None, description="博客id允许为空" )] commentname:Annotated[str,Field( diff --git a/routers/commentmanage.py b/routers/commentmanage.py index 5e53708..9db782c 100644 --- a/routers/commentmanage.py +++ b/routers/commentmanage.py @@ -7,23 +7,40 @@ router = APIRouter( prefix="/comments", tags=['评论管理'] ) -# 获取列表 -@router.get("/list") -@limiter.limit("10/minute") -async def comment_list(request: Request,): - select_query = "SELECT id,blog_id,commentname,email,commenturl,commentcontent,create_at FROM comments;" - comment_list = fetch_all(select_query) - return response_success(comment_list, "comment get list success") + # 新增 @router.post("/add") @limiter.limit("10/minute") async def comment_add(request: Request,comment:Comment): - insert_query="""INSERT INTO comments (blog_id,commentname,email,commenturl,commentcontent) VALUES(%s,%s,%s,%s)""" - insert_value=(comment.blog_id,comment.commentname,comment.email,comment.commenturl,comment.commentcontent) + insert_query="""INSERT INTO comments (parent_id,blog_id,commentname,email,commenturl,commentcontent) VALUES(%s,%s,%s,%s)""" + insert_value=(comment.parent_id,comment.blog_id,comment.commentname,comment.email,comment.commenturl,comment.commentcontent) execute_query(insert_query,insert_value) return response_success(data=comment,message="comment create success") + +def build_comment_tree(comments: list[dict[str, any]], parent_id: int = None) -> list[dict[str, any]]: + tree = [] + for comment in comments: + if comment['parent_id'] == parent_id: + children = build_comment_tree(comments, comment['id']) + if children: + comment['children'] = children + tree.append(comment) + return tree + +@router.get("/list") +@limiter.limit("10/minute") +async def comment_list(request: Request, blog_id: int = Query(..., description="ID of the blog to filter comments")): + select_query = """ + SELECT id, parent_id, blog_id, commentname, email, commenturl, commentcontent, create_at + FROM comments + WHERE blog_id = %s; + """ + comments = fetch_all(select_query, (blog_id,)) + comment_tree = build_comment_tree(comments) + return response_success(comment_tree, "comment get list success") + # # 单条数据查询 # @router.get("/list/search") # @limiter.limit("10/minute")