11from sqlalchemy .orm import Session
2- from models .comment import Comment
2+ from models .comment import Comment , CommentLike
33from schemas .comment import CommentCreate
44from datetime import datetime
55from typing import List
@@ -22,23 +22,33 @@ def create_comment(db: Session, user_id: int, discussion_id: int, comment_data:
2222def add_like_to_comment (db : Session , comment_id : int , user_id : int ):
2323 comment = db .query (Comment ).filter (Comment .comment_id == comment_id ).first ()
2424
25- if not comment :
26- return None # 댓글이 존재하지 않음
27-
28- # 좋아요 토글: 0이면 +1, 1 이상이면 -1
29- if comment .like == 0 :
30- comment .like += 1 # 좋아요 추가
25+ # 사용자가 이미 좋아요를 눌렀는지 확인
26+ existing_like = db .query (CommentLike ).filter (
27+ CommentLike .comment_id == comment_id ,
28+ CommentLike .user_id == user_id
29+ ).first ()
30+
31+ if existing_like :
32+ # 이미 눌렀다면 삭제 (좋아요 취소)
33+ db .delete (existing_like )
34+ comment .like -= 1
35+ liked = False
3136 else :
32- comment .like -= 1 # 좋아요 취소
37+ # 좋아요 추가
38+ new_like = CommentLike (comment_id = comment_id , user_id = user_id )
39+ db .add (new_like )
40+ comment .like += 1
41+ liked = True
3342
3443 db .commit ()
3544 db .refresh (comment )
3645
37- return comment
46+ return { "comment_id" : comment_id , "like" : comment . like , "liked" : liked }
3847
3948# 사용자가 좋아요 누른 답글 조회
4049def get_liked_comments_by_user (db : Session , user_id : int ):
41- return db .query (Comment ).filter (Comment .user_id == user_id , Comment .like > 0 ).all ()
50+ return db .query (Comment ).join (CommentLike , Comment .comment_id == CommentLike .comment_id )\
51+ .filter (CommentLike .user_id == user_id ).all ()
4252
4353# 토론에 대한 모든 답글 조회
4454def get_comments_by_discussion_id (db : Session , discussion_id : int ) -> List [Comment ]:
0 commit comments