PHP
Performing Aggregates on Eloquent Relationships (e.g., `withCount`, `withSum`)
Learn to efficiently retrieve aggregate values like counts, sums, averages, min, or max from related Eloquent models directly within your main query.
<?php
// app/Models/Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}
// app/Models/Comment.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
// Assume comments have a 'likes' column
}
// Example: Get all posts and their comment counts
$postsWithCounts = Post::withCount('comments')->get();
foreach ($postsWithCounts as $post) {
echo "Post: {$post->title}, Comments: {$post->comments_count}
";
}
// Example: Get all posts and the total likes across their comments
$postsWithLikeSums = Post::withSum('comments', 'likes')->get();
foreach ($postsWithLikeSums as $post) {
echo "Post: {$post->title}, Total Comment Likes: {$post->comments_sum_likes}
";
}
// You can also use withMin, withMax, withAvg for other aggregates
// Post::withAvg('comments', 'rating')->get();
How it works: Eloquent provides convenient methods like `withCount()`, `withSum()`, `withMin()`, `withMax()`, and `withAvg()` to retrieve aggregate values for related models. These methods add a `_count`, `_sum_{column}`, etc., attribute to the parent model, populated by a single optimized query, effectively solving the N+1 problem for aggregates. This avoids loading all related models just to perform a count or sum, significantly improving performance.