【问题标题】:users & roles both are different entites in symfony 2.8用户和角色都是 symfony 2.8 中的不同实体
【发布时间】:2016-06-15 17:36:06
【问题描述】:

我正在开发一个项目,我需要为用户和角色提供解决方案,它们都是不同的实体。

用户实体

user
id
fname
lname
email

角色实体

roles
id
roles

user_roles 实体

id
user_id
role_id

【问题讨论】:

    标签: symfony doctrine entity


    【解决方案1】:

    您需要创建实现 RoleInterface 的 Role 类,并将其添加到具有 ManyToMany 关系的 User 类中,并在 getRoles() 方法中返回角色数组,就是这样。

    【讨论】:

      【解决方案2】:

      使用多对多关系,因为它记录在 here。在这种情况下,您只需要两个实体:userrole,其他所有内容都通过原则进行管理。请记住,在数据库中您仍然需要 3 个表(userroleuser_role)。

      例子:

      /** @Entity */
      class User
      {
          // ...
      
          /**
           * @ManyToMany(targetEntity="Role")
           * @JoinTable(name="user_role",
           *      joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
           *      inverseJoinColumns={@JoinColumn(name="role_id", referencedColumnName="id", unique=true)}
           *      )
           */
          private $roles;
      
          public function __construct()
          {
              $this->roles = new \Doctrine\Common\Collections\ArrayCollection();
          }
      

      【讨论】:

        【解决方案3】:

        这是我的用户实体中的 getRoles 函数的示例:

            /**
             * Returns the user roles.
             *
             * @return array The roles
             */
            public function getRoles()
            {
                $now = new \DateTime();
                $roles = $this->roles;
        
                foreach ($this->getGroups() as $group) {
                    $roles = array_merge($roles, $group->getRoles());
                }
        
                foreach ($this->getUserApplicationsPermissions() as $uap) {
                    if (
                        $uap->getPermanent() ||
                        ($uap->getStartDate() < $now && !$uap->getEndDate()) ||
                        ($uap->getStartDate() < $now && $uap->getEndDate() > $now)
                    ) {
                        $roles = array_merge($roles, array($uap->getApplicationPermission()->getLibelle()));
                    }
                }
        
                // we need to make sure to have at least one role
                $roles[] = static::ROLE_DEFAULT;
        
                return array_unique($roles);
            }
        

        我的目标是处理 fos 用户角色 + 自制角色系统,有一段时间的激活或永久复选框。

        【讨论】:

          猜你喜欢
          • 2016-08-04
          • 2015-06-14
          • 2017-03-18
          • 2018-10-16
          • 1970-01-01
          • 2015-11-23
          • 2012-05-05
          • 2015-11-02
          • 1970-01-01
          相关资源
          最近更新 更多