diff --git a/src/main/java/com/back/domain/board/post/entity/Post.java b/src/main/java/com/back/domain/board/post/entity/Post.java index 1365c631..863e21ce 100644 --- a/src/main/java/com/back/domain/board/post/entity/Post.java +++ b/src/main/java/com/back/domain/board/post/entity/Post.java @@ -62,6 +62,10 @@ public void addPostCategoryMapping(PostCategoryMapping mapping) { this.postCategoryMappings.add(mapping); } + public void removePostCategoryMapping(PostCategoryMapping mapping) { + this.postCategoryMappings.remove(mapping); + } + public void addLike(PostLike like) { this.postLikes.add(like); } @@ -93,11 +97,23 @@ public void update(String title, String content) { this.content = content; } - // TODO: 진짜로 바뀐 카테고리만 추가/삭제하도록 개선 /** 카테고리 일괄 업데이트 */ - public void updateCategories(List categories) { - this.postCategoryMappings.clear(); - categories.forEach(category -> new PostCategoryMapping(this, category)); + public void updateCategories(List newCategories) { + List currentCategories = this.getCategories(); + + // 제거 대상 + List toRemove = this.getPostCategoryMappings().stream() + .filter(mapping -> !newCategories.contains(mapping.getCategory())) + .toList(); + + // 추가 대상 + List toAdd = newCategories.stream() + .filter(category -> !currentCategories.contains(category)) + .toList(); + + // 실행 + toRemove.forEach(this::removePostCategoryMapping); + toAdd.forEach(category -> new PostCategoryMapping(this, category)); } /** 좋아요 수 증가 */ diff --git a/src/main/java/com/back/domain/board/post/service/PostService.java b/src/main/java/com/back/domain/board/post/service/PostService.java index b5db7766..d290d819 100644 --- a/src/main/java/com/back/domain/board/post/service/PostService.java +++ b/src/main/java/com/back/domain/board/post/service/PostService.java @@ -49,17 +49,18 @@ public PostResponse createPost(PostRequest request, Long userId) { // Post 생성 Post post = new Post(user, request.title(), request.content(), request.thumbnailUrl()); + // Post 저장 + Post saved = postRepository.save(post); + // Category 매핑 if (request.categoryIds() != null) { List categories = postCategoryRepository.findAllById(request.categoryIds()); if (categories.size() != request.categoryIds().size()) { throw new CustomException(ErrorCode.CATEGORY_NOT_FOUND); } - post.updateCategories(categories); + saved.updateCategories(categories); } - // Post 저장 및 응답 반환 - Post saved = postRepository.save(post); return PostResponse.from(saved); }