2017-01-13 7 views
0

したがって、userテーブル、roleテーブル、およびこれらの2つの中間テーブルuser_roleがあります。これは最初の2つのテーブル間の多対多の関係です。 特定の役割を持つユーザーの数を返したいと思いますが、それを正しく取得できないようです。ピボットテーブルによるテーブルの列の返り値Laravel 5.2

マイ移行:

ユーザー:

Schema::create('users', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->timestamps(); 
     $table->string('email')->unique(); 
     $table->string('username')->unique(); 
     $table->string('password'); 
}); 

役割:

Schema::create('roles', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->timestamps(); 
     $table->string('name', 40); 
     $table->string('description', 255); 
    }); 

USER_ROLE:それらの間の

Schema::create('user_role', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->timestamps(); 
     $table->integer('user_id'); 
     $table->integer('role_id'); 
    }); 

関係:

public function users(){ //in role model 
     return $this->belongsToMany('App\User', 'user_role', 'role_id', 'user_id')->withTimestamps(); 
    } 

public function roles(){ //in user model 
     return $this->belongsToMany('App\Role', 'user_role', 'user_id', 'role_id')->withTimestamps(); 
    } 

役割シーダー:コントローラで

public function run() 
    { 
     Role::create([ 
      'id'   => 1, 
      'name'   => 'Admin', 
      'description' => 'Admin User.' 
     ]); 
     Role::create([ 
      'id'   => 2, 
      'name'   => 'Vendor', 
      'description' => 'Vendor User.' 
     ]); 
     Role::create([ 
      'id'   => 3, 
      'name'   => 'User', 
      'description' => 'Simple User.' 
     ]); 
    } 

:ビューで

public function adminDashboard(){ 
     $users = User::all(); 
     return view('admin.dashboard')->withUsers($users); 
    } 

{{ $users->count() }} 

これは明らかに、ユーザテーブル内のユーザーの合計数を返します。特定の役割を持つユーザーの数を返す方法に関するアイデアですか?役割を反復し、ユーザーの数を表示するには

答えて

1

使用$role->users()->count()

、あなたはこれを使用することができます:あなたのダッシュボードビューで

public function adminDashboard(){ 
    $roles = App\Role::all(); 
    return view('admin.dashboard', compact('roles')); 
} 

:いないようです

@foreach ($roles as $role) 
    <p>Role {{ $role->name }} has {{ $role->users()->count() }} users</p> 
@endforeach 
+0

を助けるために。エラーを返します。メソッドのユーザーは存在しません。 – daino92

+0

しかし、ロールモデルのpublic関数users()があると述べました。 試してみてください。$ role = Role :: find(1); echo $ role-> users() - > count() – Paras

+0

あなたは正しいです。しかし、まだ...どんな考えが起こっているのですか? – daino92

関連する問題