File tree Expand file tree Collapse file tree 1 file changed +17
-10
lines changed Expand file tree Collapse file tree 1 file changed +17
-10
lines changed Original file line number Diff line number Diff 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
You can’t perform that action at this time.
0 commit comments