1
1
from sqlalchemy .orm import Session
2
- from models .comment import Comment
2
+ from models .comment import Comment , CommentLike
3
3
from schemas .comment import CommentCreate
4
4
from datetime import datetime
5
5
from typing import List
@@ -22,23 +22,33 @@ def create_comment(db: Session, user_id: int, discussion_id: int, comment_data:
22
22
def add_like_to_comment (db : Session , comment_id : int , user_id : int ):
23
23
comment = db .query (Comment ).filter (Comment .comment_id == comment_id ).first ()
24
24
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
31
36
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
33
42
34
43
db .commit ()
35
44
db .refresh (comment )
36
45
37
- return comment
46
+ return { "comment_id" : comment_id , "like" : comment . like , "liked" : liked }
38
47
39
48
# 사용자가 좋아요 누른 답글 조회
40
49
def 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 ()
42
52
43
53
# 토론에 대한 모든 답글 조회
44
54
def get_comments_by_discussion_id (db : Session , discussion_id : int ) -> List [Comment ]:
0 commit comments