获取所有在 Laravel 中具有角色的用户

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22487324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:13:17  来源:igfitidea点击:

Get all users with role in Laravel

phplaravellaravel-4eloquentroles

提问by jdfauw

I'm working in this Laravel project which has this structure

我正在这个具有这种结构的 Laravel 项目中工作

users: id | first_name |...

用户:id | 名字|...

roles: id | name

角色:id | 姓名

assigned_roles: id | user_id | role_id

分配的角色:id | 用户 ID | role_id

I think this is quite obvious :p

我认为这很明显:p

User model

用户模型

class User extends ConfideUser {
use HasRole;

public function Roles(){
    return $this->belongsToMany('Role','assigned_roles');
}

Role model

好榜样

class Role extends EntrustRole
{
public function Users()
{
    return $this->belongsToMany('User','assigned_roles');
}


} 

I'm looking for a way to get all users with a specified role in this case 'Teacher'. I've tried this:

在这种情况下,我正在寻找一种方法来让所有用户都具有指定的角色“老师”。我试过这个:

$students = User::with(array('Roles' => function($query) {
        $query->where('name','Teacher');
    }))
    ->get();
    return $students;

but this always returns an array of all users.

但这总是返回所有用户的数组。

would anyone know why that's so? Thanks!

有谁知道为什么会这样?谢谢!

回答by duellsy

What you're currently asking laravel for in your $studentsquery, is 'give me all the students, and for each student get me all of their roles if the role is teacher'

您目前在$students查询中要求 laravel是“给我所有的学生,如果角色是老师,则为每个学生让我获得他们的所有角色”

Try using the whereHas

尝试使用 whereHas

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

This should get you the users, but only where they have a role where the name is teacher.

这应该让您成为用户,但仅限于他们拥有名为老师的角色的地方。

回答by Deepak singh Thakur

Try This.

尝试这个。

Role::where('rolename', 'user')->first()->users()->get()