$commentIds * @return array> */ public function forComments(iterable $commentIds, ?int $userId = null): array { $ids = collect($commentIds) ->map(static fn ($id): int => (int) $id) ->filter(static fn (int $id): bool => $id > 0) ->unique() ->values() ->all(); if ($ids === []) { return []; } $counts = DB::table('comment_reactions') ->whereIn('comment_id', $ids) ->selectRaw('comment_id, reaction, COUNT(*) as total') ->groupBy('comment_id', 'reaction') ->get() ->groupBy('comment_id'); $mine = collect(); if ($userId !== null) { $mine = DB::table('comment_reactions') ->whereIn('comment_id', $ids) ->where('user_id', $userId) ->get(['comment_id', 'reaction']) ->groupBy('comment_id'); } $result = []; foreach ($ids as $commentId) { $commentCounts = $counts->get($commentId, collect())->keyBy('reaction'); $commentMine = $mine->get($commentId, collect())->pluck('reaction')->flip(); $totals = []; foreach (ReactionType::cases() as $type) { $slug = $type->value; $totals[$slug] = [ 'emoji' => $type->emoji(), 'label' => $type->label(), 'count' => (int) ($commentCounts->get($slug)->total ?? 0), 'mine' => $commentMine->has($slug), ]; } $result[$commentId] = $totals; } return $result; } }