使用 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 前端工作流等。
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 2

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

3个月前 评论

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