【问题标题】:Fosuser bundle - setting role to userFosuser bundle - 为用户设置角色
【发布时间】:2016-12-09 20:42:43
【问题描述】:

我想为用户设置角色。我使用以下代码:

    $user = this->getDoctrine()->getRepository('BlogBundle:User')->findOneById('11');
    $em = $this->getDoctrine()->getManager();
    $t=array('ROLE_ADMIN');
    $user->setRoles($t);
    $em->persist($user);
    $em->flush();
    return new Response('okk');

当我设置“ROLE_ADMIN”时,一切正常,但当我设置“ROLE_USER”时,数据库单元格为空。为什么?

提前感谢您的帮助。

【问题讨论】:

  • stackoverflow.com/questions/18779655/… 默认情况下,创建的用户具有 ROLE_USER 角色,该角色保存在 DB 中,如转换为 JSON 的空数组 a:0:{} 列的值是空值还是表示空 json 数组?

标签: symfony fosuserbundle


【解决方案1】:

你的用户表中的角色列,应该有

a:0:{}

仅适用于角色 ROLE_USER 的用户

程序化的检查方式。

检查用户是否具有特定角色(包括 ROLE_USER )

if ($this->get('security.context')->isGranted('ROLE_USER')) {
    // the user has the ROLE_USER role
}

还有

$user->getRoles()

另一种方法来仔细检查用户是否真的有ROLE_USER

php app/console fos:user:promote 

出现提示时,输入用户名,后跟ROLE_USER

应该说明

用户“example@example.com”确实已经拥有“ROLE_USER”角色。

【讨论】:

    【解决方案2】:

    在 FOS 用户包中,所有用户都有ROLE_USER 角色。添加/保存此角色将是多余的。

    如果您在 FOSUserBundle 的代码库中查找它,该角色在 UserInterface 类中的别名为 ROLE_DEFAULT

    【讨论】:

    • 谢谢大家的回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多