简体   繁体   中英

How do I get all Users with Roles where role = 'admin' using eloquent along with Entrust?

I'm using Laravel Entrust Package https://github.com/Zizaco/entrust I want to get all the users with their roles like this

name | role

Ryan | admin
Megan | admin

Table structure

users 
id,name,email,password

roles, 
id,name

role_user (pivot table)
id,user_id

I tried this but doesn't work

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

Error

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

I don't want to use neither RAW queries nor this

$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();

Is there any other way?

Use whereHas

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

Use this, it'll retrieve all user with admin role

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM