Skip to content

Commit 3c0d611

Browse files
committed
[FIX] 답글 좋아요 수 반영
1 parent 6d5c888 commit 3c0d611

File tree

2 files changed

+27
-10
lines changed

2 files changed

+27
-10
lines changed

crud/comment.py

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from sqlalchemy.orm import Session
2-
from models.comment import Comment
2+
from models.comment import Comment, CommentLike
33
from schemas.comment import CommentCreate
44
from datetime import datetime
55
from typing import List
@@ -22,23 +22,33 @@ def create_comment(db: Session, user_id: int, discussion_id: int, comment_data:
2222
def 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
# 사용자가 좋아요 누른 답글 조회
4049
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()
4252

4353
# 토론에 대한 모든 답글 조회
4454
def get_comments_by_discussion_id(db: Session, discussion_id: int) -> List[Comment]:

models/comment.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,10 @@ class Comment(Base):
1212
like = Column(Integer, default=0, nullable=False)
1313
created_date = Column(DateTime, server_default=func.now(), nullable=False)
1414
updated_date = Column(DateTime, onupdate=func.now(), nullable=True)
15+
16+
class CommentLike(Base):
17+
__tablename__ = "comment_likes"
18+
19+
comment_likes_id = Column(BigInteger, primary_key=True, autoincrement=True, nullable=False)
20+
comment_id = Column(BigInteger, ForeignKey("comments.comment_id", ondelete="CASCADE"), nullable=False)
21+
user_id = Column(BigInteger, ForeignKey("users.user_id", ondelete="CASCADE"), nullable=False)

0 commit comments

Comments
 (0)