【问题标题】:Laravel 5.0: Pivot table issueLaravel 5.0:数据透视表问题
【发布时间】: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_id 2 的用户,对吗?
  • 是的!数据透视表上 role_id 为 2 的用户

标签: php laravel laravel-5 pivot-table


【解决方案1】:

如果您正在寻找拥有 role_id2

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

它会带来有roles2的用户

【讨论】:

  • 哇!非常感谢阿里夫!你太棒了!!
  • 还要对 with 语句进行闭包,否则您将获得附加到所选用户的所有角色。
【解决方案2】:

试试这个查询。

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

【讨论】:

    【解决方案3】:

    对于拥有 role_id(dynamic) 的用户是:

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

    【讨论】:

      猜你喜欢
      • 2015-09-21
      • 2018-12-16
      • 2019-07-04
      • 2021-03-09
      • 2018-04-10
      • 2017-07-03
      • 2021-07-27
      • 2020-08-04
      相关资源
      最近更新 更多