laravel5.3统计 withCount()方法的使用

在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();

posted @ 2017-10-27 11:39  寞小陌  阅读(12587)  评论(2编辑  收藏  举报