通过数据透视表Laravel 5.2返回表格列的计数

时间:2017-01-13 21:50:41

标签: php laravel laravel-5

所以我有一个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() }}

这显然会返回用户表中用户的总数。关于如何返回具有特定角色的用户数的任何想法?

1 个答案:

答案 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