php 如何在 Yii2 中获取用户角色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25247675/
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
How to get user role in Yii2?
提问by b24
How to get user role in Yii2?
如何在 Yii2 中获取用户角色?
I searched and read Yii2 guidebut I didn't find any solution.
我搜索并阅读了Yii2 指南,但没有找到任何解决方案。
回答by Manquer
You can get Roles for an user by using getRolesByUserfunction
您可以使用getRolesByUser函数为用户获取角色
You can use it like this
你可以像这样使用它
\Yii::$app->authManager->getRolesByUser($user_id);
回答by d4v1d
You can use:
您可以使用:
Yii::$app->authManager->getRolesByUser(Yii::$app->user->getId());
回答by elfarqy
I use :
我用 :
if (\Yii::$app->authManager-> getAssignment($role,$rule_id))
for filtering user id
and role
in rbac, More details on Yii2 Documentation
用于过滤user id
和role
rbac,有关Yii2 文档的更多详细信息
回答by Denis Solovyov
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.
另一个如何获取用户角色的示例:Yii::$app->getUser()->identity->role;
如果您的用户表中有名为“role”的列,它就可以工作。
回答by Mohan Prasad
You can use :
您可以使用 :
$user =[];
$userAssigned = Yii::$app->authManager->getAssignments(user_id);
foreach($userAssigned as $userAssign){
$user[] = $userAssign->roleName;
}
回答by Imtiaz
If you're using amnah/yii2-usermodule, you can use this:
如果你使用amnah/yii2-user模块,你可以使用这个:
Yii::$app->user->identity->role->name
It will give you the current user role name
它将为您提供当前用户角色名称
回答by Alliswell
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
回答by Awais Mustafa
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. Now you can check that if user is admin or editor or member.
这将是您用户在身份验证分配中的角色。现在您可以检查用户是管理员还是编辑者或成员。