【问题标题】:How do I get all Users with Roles where role = 'admin' using eloquent along with Entrust?如何使用 eloquent 和 Entrust 获得所有角色为角色 = 'admin' 的用户?
【发布时间】:2015-08-24 20:15:28
【问题描述】:

我正在使用 Laravel Entrust 包https://github.com/Zizaco/entrust 我想让所有用户都拥有这样的角色

name | role

Ryan | admin
Megan | admin

表结构

users 
id,name,email,password

roles, 
id,name

role_user (pivot table)
id,user_id

我试过了,但没有用

$users = User::with('roles')->where('roles.name','=','admin')->get();

错误

Column not found: 1054 Unknown column 'roles.name' in 'where clause' (SQL: select * from users where roles.name = admin)

我既不想使用 RAW 查询也不想使用这个

$users = DB::table('users')->select('users.name as username', 'role.name as role')->with('roles')->join('roles', 'roles.user_id', '=', 'users.id')->where('roles.name', 'admin')->get();

还有其他方法吗?

【问题讨论】:

    标签: php laravel eloquent laravel-5


    【解决方案1】:

    使用whereHas

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

    【讨论】:

      【解决方案2】:

      使用这个,它将检索所有具有管理员角色的用户

      $users = User::with(['roles' => function($query)
      {
          $query->where('name','=','admin');
      }])->get();
      

      【讨论】:

        猜你喜欢
        • 2014-05-08
        • 2017-02-06
        • 2015-12-27
        • 2023-03-21
        • 1970-01-01
        • 2012-04-04
        • 2015-04-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多