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