Please format your code so that it's readable.
Dec 3, 2024
4
Level 1
Laravel Eloquent: Eager Loading and Counting Votes for Comments
User has many posts, post has many comments, and there's a pivot table "comment_votes" with the following structure:
$table->id();
$table->foreignId('user_id');
$table->foreignId('comment_id');
$table->enum('type', ['upVote', 'downVote']);
I want to get the count of upvotes and downvotes for every comment within the index() function of my PostController:
public function index() {
$posts = Post::with('comments.user','user.postVotes') ->withCount('upvote','downvote')->latest()->get(); /upvote and downvote are two relationships are used to retrieve the vote count for a post./
}
I'm particularly interested in optimizing the query to minimize database queries and improve performance.
Please or to participate in this conversation.