laravel - 为什么引入 loadCount() 及其在 laravel 中的实际用法
问题描述
我已经在这里阅读了文档: https ://github.com/laravel/framework/pull/25997
我想知道的是通过使用withCount()
我们只是加载记录计数而不是获取所有关系数据。
那么通过使用loadCount()
我们可以做些什么呢?
请用简单的话简短地解释一下。谢谢
解决方案
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);
推荐阅读
- java - 无法使用 JUnit 打印测试用例中的所有测试结果
- powershell - 查找和替换值
- html - 带有 CSS 网格的表格
- javascript - 使用 contenteditable 创建自动调整大小的文本区域
- python - 如何更改 DataFrame.hist() 或 DataFrame.plot.hist( subplots = True ) 函数中各个直方图的颜色?
- python - 用诗歌安装 pycocotools(不符合 PEP 517/518)
- reactjs - React-UseState hook->状态更新不会立即重新渲染页面
- azure - Graph API 过期订阅仍然可以从订阅列表中检索
- javascript - How to Copy Row to Another SPREADSHEET based on Certain Value
- python - 如何在 Python 中通过橡皮筋法去除基线?