简体   繁体   English

如何在Yii2中获得用户角色?

[英]How to get user role in Yii2?

How to get user role in Yii2? 如何在Yii2中获得用户角色?

I searched and read Yii2 guide but I didn't find any solution. 我搜索并阅读了Yii2指南,但我没有找到任何解决方案。

You can get Roles for an user by using getRolesByUser function 您可以使用getRolesByUser函数为用户获取角色

You can use it like this 你可以像这样使用它

\Yii::$app->authManager->getRolesByUser($user_id);

您可以使用:

Yii::$app->authManager->getRolesByUser(Yii::$app->user->getId());

I use : 我用 :

if (\Yii::$app->authManager-> getAssignment($role,$rule_id))

for filtering user id and role in rbac, More details on Yii2 Documentation 用于过滤rbac中的user idrole ,有关Yii2文档的更多详细信息

One more example how to get user role: 另一个示例如何获得用户角色:
Yii::$app->getUser()->identity->role;
It works if you have column with name "role" in your user table. 如果您的用户表中包含名为“role”的列,则它可以正常工作。

You can use : 您可以使用 :

 $user =[];
 $userAssigned = Yii::$app->authManager->getAssignments(user_id);
 foreach($userAssigned as $userAssign){
      $user[] = $userAssign->roleName;
 } 

If you're using amnah/yii2-user module, you can use this: 如果你正在使用amnah / yii2-user模块,你可以使用:

Yii::$app->user->identity->role->name

It will give you the current user role name 它将为您提供当前用户角色名称

The good and more visual decision will be setting constants of all roles. 好的和更直观的决定将是设定所有角色的常数。

$userID = $user->getId();
array_keys(Yii::$app->authManager->getRolesByUser($userID))[0] == User::ROLE_NAME

You can get role of the user by using createcommand. 您可以使用createcommand获取用户的角色。

    $roleModel = Yii::$app->db
    ->createCommand("Select * from auth_assignment where user_id='889'")
    ->queryOne();

    echo $roleModel['item_name'];

This will you user's role in auth assignment. 这将是您在auth赋值中的角色。 Now you can check that if user is admin or editor or member. 现在,您可以检查用户是管理员,编辑者还是成员。

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

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