Skip to content

Commit 9e4abf3

Browse files
authored
Merge pull request #46 from mubbi/develop
Develop to main
2 parents 2aedda1 + 2650fe2 commit 9e4abf3

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

app/Services/ArticleService.php

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -180,16 +180,23 @@ public function getArticleComments(
180180
$comments->load(['user']);
181181
$comments->loadCount('replies');
182182

183-
// Load replies for each parent comment
184-
$comments->each(function (Comment $comment) use ($repliesPerPage) {
185-
$replies = $comment->replies()
186-
->with('user')
187-
->withCount('replies')
188-
->orderBy('created_at')
189-
->limit($repliesPerPage)
190-
->get();
191-
192-
$comment->setRelation('replies_page', $replies);
183+
// Collect IDs of parent comments
184+
$parentCommentIds = $comments->pluck('id');
185+
186+
// Fetch replies in batch (LIMIT repliesPerPage per parent)
187+
$replies = Comment::query()
188+
->whereIn('parent_comment_id', $parentCommentIds)
189+
->with('user')
190+
->withCount('replies')
191+
->orderBy('created_at')
192+
->get()
193+
->groupBy('parent_comment_id');
194+
195+
// Attach limited replies to each comment
196+
$comments->each(function (Comment $comment) use ($replies, $repliesPerPage) {
197+
$replyCollection = $replies[$comment->id] ?? collect();
198+
$limitedReplies = $replyCollection->take($repliesPerPage);
199+
$comment->setRelation('replies_page', $limitedReplies);
193200
});
194201

195202
// Replace the collection on paginator so it's returned with relations loaded

0 commit comments

Comments
 (0)