2016-07-17 10 views
1

テーブルuserrolesは、ピボットテーブルrole_userテーブルを使用して多対多のリレーションシップを持つとします。私は私のモデルLaravel 5多かれ少なかれ多数の関係

belongstomany関係を使用してい

どのように私は、ユーザーが役割adminstaff解決

+0

あなたはこれまでに何がありますか? – TheFallen

答えて

1

を持っているどのように多くカウントするように雄弁なクエリを作成します。

雄弁なクエリを作るために、Role.phpモデルその後

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(); 
関連する問題