使用 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();
他的原理是咋样的?你还是只是使用?
原理是子查询