Laravel 5 Laravel 5雄辩的计数多对多关系

Laravel 5 Laravel 5雄辩的计数多对多关系,laravel-5,eloquent,Laravel 5,Eloquent,假设我有一个表user和roles,使用pivot表role\u user表建立了多对多关系 我在我的模型上使用belongtomany关系 我如何做一个雄辩的查询来计算有多少用户担任了管理员和职员的角色 将此添加到Role.phpmodel public function userCount() { return $this->belongsToMany(Role::class) ->selectRaw('count(role_user.user_id) a

假设我有一个表
user
roles
,使用pivot表
role\u user
表建立了多对多关系

我在我的模型上使用
belongtomany
关系

我如何做一个雄辩的查询来计算有多少用户担任了
管理员
职员

的角色

将此添加到
Role.php
model

public function userCount() {
    return $this->belongsToMany(Role::class)
        ->selectRaw('count(role_user.user_id) as total_user')
        ->groupBy('role_id');
}
还有这个

public function getUserCountAttribute()
    {
        if ( ! array_key_exists('userCount', $this->relations)) $this->load('customerCount');

        $related = $this->getRelation('userCount')->first();

        return ($related) ? $related->total_user : 0;
    }
在那之后,提出一个雄辩的问题

$roleUsers = Role::with('userCount')->orderBy('id', 'asc')->get();

到目前为止你有什么?