Laravel 5.0:数据透视表问题


Laravel 5.0: Pivot table issue

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

我想获得一个附有特定 ID 的集合。

我的控制器

/**
 * 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'));
}

在这种情况下,我想将下面的集合放在上面的变量"讲师"中,因为下面的集合已附加到role_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"

$instructor->角色

   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"

角色.php

public function users(){
    return $this->belongsToMany('App'User');
}

用户.php

public function roles(){
    return $this->belongsToMany('App'Role')->withTimestamps();
}

英语不是我的第一语言。如果这篇文章没有意义,请留下您的评论。任何建议将不胜感激!提前感谢!

你必须使用 wherehas,如果你正在寻找有 role_id 2

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

它将带来具有roles 2

的用户

试试这个查询。

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

对于具有 role_id(动态) 的用户是:

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