使用 withCount() 计算子关系记录

使用withCount()计算子关系记录

如果您有hasMany()关系,并且您想计算“子”条目,则不要编写特殊的查询。例如,如果您在User模型上有帖子和评论,请使用Count()编写以下内容:

public function index(){    
$users = User::withCount(['posts', 'comments'])->get(); 
return view('users', compact('users'));
}

And then, in your Blade file, you will access those number with {relationship}_count properties:

@foreach ($users as $user)
<tr>    <td>{{ $user->name }}</td>  
<td class="text-center">{{ $user->posts_count }}</td> 
<td class="text-center">{{ $user->comments_count }}</td></tr>
@endforeach

You may also order by that field:

User::withCount('comments')->orderBy('comments_count', 'desc')->get();
人生就是马拉松,精彩的是后半程
running8
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 2

他的原理是咋样的?你还是只是使用?

6个月前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!