所以我有一个user
表,一个role
表和一个用于那些user_role
的中间表。它是前两个表之间的多对多关系。
我想返回具有特定角色的用户数,但我似乎无法做到正确。
我的迁移:
用户:
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() }}
这显然会返回用户表中用户的总数。关于如何返回具有特定角色的用户数的任何想法?
答案 0 :(得分: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