在laravel5.3之后可以使用withCount()這個方法。
注意:一定要是5.3版本之后,5.2和5.1都會報方法未定義
舉個栗子:
App\Post::withCount('comments')->get();
使用該方法后,會在模型中添加一個comments_count屬性,所以你就可以直接訪問該屬性就可以了得到統計數了。
foreach ($posts as $post) { echo $post->comments_count; }
你可以像添加約束條件到查詢一樣來添加多個關聯關系的“計數”:
$posts = Post::withCount(['votes', 'comments' => function ($query) {
$query->where('content', 'like', 'foo%');
}])->get();