首页 > 解决方案 > 为什么引入 loadCount() 及其在 laravel 中的实际用法

问题描述

我已经在这里阅读了文档: https ://github.com/laravel/framework/pull/25997

我想知道的是通过使用withCount()我们只是加载记录计数而不是获取所有关系数据。

那么通过使用loadCount()我们可以做些什么呢?

请用简单的话简短地解释一下。谢谢

标签: laravel

解决方案


Laravel 5.7.10 版本引入的 loadCount Eloquent 收集方法。根据laravel-news

loadCount是在 Eloquent 集合上加载关系计数的能力。在此功能之前,您只能加载关系,但现在您可以调用 loadCount() 来获取所有关系的计数。

拉取请求说明了如何通过以下示例使用 loadCount() :

$events = Event::latest()->with('eventable')->paginate();

$groups = $events->map(function ($event) {
    return $event->eventable;
})->groupBy(function ($eventable) {
    return get_class($eventable);
});

$groups[Post::class]->loadCount('comments');
$groups[Comment::class]->loadCount('hearts');

return new EventIndexResponse($events);

推荐阅读