我有bican角色插件,需要访问数据透视表。这是在我的控制器代码中

   $users = User::where('role_id','=',2)->get();


迁移角色

   Schema::create('roles', function (Blueprint $table) {
        $table->increments('id')->unsigned();
        $table->string('name');
        $table->string('slug')->unique();
        $table->string('description')->nullable();
        $table->integer('level')->default(1);
        $table->timestamps();
    });


迁移用户

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


关键迁移

   Schema::create('role_user', function (Blueprint $table) {
        $table->increments('id')->unsigned();
        $table->integer('role_id')->unsigned()->index();
        $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
        $table->integer('user_id')->unsigned()->index();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->timestamps();
    });

最佳答案

如果您与用户和角色之间的关系是多对多的,则表明您在错误地查询User。正确的查询将为:

$users = User::whereHas('roles', function($q) {
                    $q->where('role_id', 2);
              })
              ->get();


然后,您可以获取用户的角色为:

foreach($users as $user) {
    $user->roles; // returns collection of roles
}

08-26 15:16