laravel withCount 统计关联数量

 

 

roleModel定义关联 hasmany 

public function users(){ return $this->hasMany('App\Models\Users', 'role_id', 'role_id'); }

return $this->query()->withCount("users")->get();

  

  

 

统计关联数量,单个用法

$posts = Post::withCount('comments')->orderBy('id','desc')->paginate(6);

多个用法

$posts = Post::withCount(['comments','zans'])->orderBy('id','desc')->paginate(6);

调用

$post->comments_count

posted @ 2019-10-09 17:44  brady-wang  阅读(1624)  评论(0编辑  收藏  举报