【发布时间】:2016-04-20 07:08:01
【问题描述】:
我是 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'));
}
在这种情况下,我想把下面的集合放在上面的变量“instructors”中,因为下面的集合已经附加到role_id 2,它是一个instructor。
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"
Role.php
public function users(){
return $this->belongsToMany('App\User');
}
User.php
public function roles(){
return $this->belongsToMany('App\Role')->withTimestamps();
}
英语不是我的母语。如果这篇文章没有意义,请留下您的cmets。任何意见,将不胜感激!提前致谢!
【问题讨论】:
-
您想要拥有
role_id2的用户,对吗? -
是的!数据透视表上 role_id 为 2 的用户
标签: php laravel laravel-5 pivot-table