Laravel 8 关联模型计数
如果想要只计算关联结果的统计数量而不需要真实加载它们,可以使用 withCount
方法,它将放在结果模型的 {relation}_count
列。示例如下:
$posts = App\Models\Post::withCount('comments')->get();
foreach ($posts as $post) {
echo $post->comments_count;
}
可以像给查询添加限制一样为多个关系添加「计数」:
use Illuminate\Database\Eloquent\Builder;
$posts = App\Models\Post::withCount(['votes', 'comments' => function (Builder $query) {
$query->where('content', 'like', 'foo%');
}])->get();
echo $posts[0]->votes_count;
echo $posts[0]->comments_count;
还可以给关联计数结果起别名,这允许你在同一关联上添加多个计数:
use Illuminate\Database\Eloquent\Builder;
$posts = App\Models\Post::withCount([
'comments',
'comments as pending_comments_count' => function (Builder $query) {
$query->where('approved', false);
},
])->get();
echo $posts[0]->comments_count;
echo $posts[0]->pending_comments_count;
如果将 withCount
和 select
查询组装在一起,请确保在 select
方法之后调用 withCount
:
$posts = App\Models\Post::select(['title', 'body'])->withCount('comments')->get();
echo $posts[0]->title;
echo $posts[0]->body;
echo $posts[0]->comments_count;
此外,使用 loadCount
方法,您可以在父模型被加载后使用关联计数:
$book = App\Models\Book::first();
$book->loadCount('genres');
如果您需要在预加载查询上设置额外的查询约束,您可以传递一个希望加载的关联数组。数组值应该是 Closure
实例,它接收查询生成器实例:
$book->loadCount(['reviews' => function ($query) {
$query->where('rating', 5);
}])