简体   繁体   English

是否可以在Laravel中选择具有管理员角色或主持人的用户?

[英]Is it possible to select users with admin role or moderator in Laravel?

I need to select all users with admin or moderator role. 我需要选择所有具有管理员或主持人角色的用户。 But when I try this code $user = Role::with('users')->where('name', '=', 'admin')->orWhere('name', '=', 'moderator')->get(); 但是当我尝试此代码时$user = Role::with('users')->where('name', '=', 'admin')->orWhere('name', '=', 'moderator')->get(); it's order them by roles like this: 通过如下角色对它们进行排序:

    Array
    (
        [0] => Array
            (
                [id] => 1
                [name] => admin
                [users] => Array
                    (
                        [0] => Array
                            (
                                [id] => 1
                                [name] => admin
                                [pivot] => Array
                                    (
                                        [role_id] => 1
                                        [user_id] => 1
                                    )

                            )

                    )

            )

        [1] => Array
            (
                [id] => 2
                [name] => moderator
                [users] => Array
                    (
                        [0] => Array
                            (
                                [id] => 2
                                [name] => Moderator
                                [pivot] => Array
                                    (
                                        [role_id] => 2
                                        [user_id] => 2
                                    )

                            )
                    )

            )

    )

Is there any way to get all users in one array with role admin or moderator? 有什么办法可以让所有用户与管理员或主持人一起使用?

Yeah. 是啊。 Since you are looking for users based on their role, start from the user instead. 由于您是根据用户的角色寻找用户的,因此请从该用户开始。

$users = User::with('roles')->whereHas('roles', function($q)
{
    $q->whereIn('name', ['admin', 'moderator']);
})->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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