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

18

我正在处理这个采用 Laravel 框架的项目,其结构如下:

users: id | first_name |...

roles: id | name

assigned_roles: id | user_id | role_id

我认为这相当明显 :p

User 模型

class User extends ConfideUser {
use HasRole;

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

榜样

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


} 

我正在寻找一种方法来获取所有在此情况下具有指定角色('Teacher')的用户。我已经尝试了以下代码:

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

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

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

6个回答

47

您目前在laravel中查询$students的要求是:“给我所有学生,对于每个学生,如果角色是教师,则获取其所有角色”

尝试使用whereHas

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

这应该可以让您获取用户,但仅限于他们具有称为“teacher”的角色的情况下。


1
它解决了问题 :) - Qazi
有没有其他方法可以检索它,因为这可能会导致性能问题。我们是否应该考虑在用户ID上使用索引来处理角色? - Deepesh Thapa
你可以使用这个非常好的包,https://github.com/mpyw/eloquent-has-by-non-dependent-subquery - Gabriel Borges Oliveira

6

5

如果您想获取所有用户及其潜在角色列表:

$authorizedRoles = ['Teacher', 'Professor', 'Super professor'];

$users = User::whereHas('roles', static function ($query) use ($authorizedRoles) {
                    return $query->whereIn('name', $authorizedRoles);
                })->get();

3

试试这个。

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

0
如果您正在使用laravel-permission包, 在控制器中,
$rolesWithUserCount = Role::withCount('users')->get();

在 Blade 文件中,

@foreach ($rolesWithUserCount as $item)
          {{ $item->name }}
          {{$item->users_count }}
@endforeach

输出:

Role1 Role1Count 
Role2 Role2Count
 ....

更多信息: 访问:https://laravel.com/docs/7.x/eloquent-relationships#counting-related-models


0
这将完全按照预期运行:
$users = User::whereHas('roles' => function($q){$q->where('name', 'Teacher');})->get();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接