Php Laravel 5.0:数据透视表问题

Php Laravel 5.0:数据透视表问题,php,laravel,laravel-5,pivot-table,Php,Laravel,Laravel 5,Pivot Table,我是Laravel框架的绝对初学者。我遇到了一个与透视表有关的问题 我想要一个带有特定id的集合 MyController /** * Show the form for creating a new resource. * * @return Response */ public function create(){ $loggedInUser = \Auth::user(); $users = User::lists('first_name', 'id');

我是Laravel框架的绝对初学者。我遇到了一个与透视表有关的问题

我想要一个带有特定id的集合

MyController

/**
 * Show the form for creating a new resource.
 *
 * @return Response
 */
public function create(){

    $loggedInUser = \Auth::user();  
    $users = User::lists('first_name', 'id');
    $instructors = // Here comes a collection that has a role_id "2" on the pivot table.
                  //This is where I have no idea what to put 

    return view('courses.create', compact('loggedInUser', 'users', 'instructors'));
}
在本例中,我希望将下面的集合放在上面的变量“讲师”中,因为下面的集合已附加到角色_id 2,该角色是讲师

   id: "2",
   first_name: "alex",
   last_name: "powder",
   email: "alex@example.com",
   ID: "819763758",
   created_at: "2016-04-18 21:34:12",
   updated_at: "2016-04-19 19:30:48"
$讲师->角色

   id: "2",
   name: "instructor",
   created_at: "2016-04-18 21:34:13",
   updated_at: "2016-04-18 21:34:13",
   pivot: <Illuminate\Database\Eloquent\Relations\Pivot #000000007a61781e00000001381bb0f0> {
           user_id: "2",
           role_id: "2",
           created_at: "2016-04-18 22:54:06",
           updated_at: "2016-04-18 22:54:06"
User.php

public function users(){
    return $this->belongsToMany('App\User');
}
public function roles(){
    return $this->belongsToMany('App\Role')->withTimestamps();
}
英语不是我的第一语言。如果这篇文章没有意义,请留下你的评论。任何建议都将不胜感激!提前谢谢

如果您正在寻找具有以下权限的用户,则必须使用
role\u id
2

它将为具有
角色的用户带来
2

如果您正在寻找具有以下权限的用户,则必须使用
role\u id
2

它将使具有
角色的用户尝试此查询

$instructors = User::whereHas('roles', function($query) {
    $query->where('roles.id', '=', 2);
})->get();
尝试此查询

$instructors = User::whereHas('roles', function($query) {
    $query->where('roles.id', '=', 2);
})->get();
对于具有角色id(动态)的用户:

对于具有角色id(动态)的用户:


您希望具有
角色\u id
2
的用户具有这些角色,对吗?是!pivot表中角色id为2的用户是否希望具有
role\u id
2
的用户具有这些角色?是!pivot表中角色id为2的用户哇!非常感谢你,阿里夫!你太棒了!!还要对with语句进行闭包,否则您将获得附加到所选用户的所有角色。哇!非常感谢你,阿里夫!你太棒了!!还要对with语句执行闭包,否则将获得附加到所选用户的所有角色。
$role_id = 2;

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