【问题标题】:Doctrine2 Entity Custom JoiningDoctrine2 实体自定义加入
【发布时间】:2015-03-27 19:28:03
【问题描述】:

我是学说实体的新手,但我有一个用户表和一个角色表,并且角色使用位掩码链接到用户。像这样

+----+----------+------+
| id | username | role |
+----+----------+------+
| 1  | admin    | 1022 |
+----+----------+------+

+----+------------+------------+
| id | role       | permission |
+----+------------+------------+
|  1 | ROLE_ADMIN |          2 |
|  2 | ROLE_DEV   |          4 |
+----+------------+------------+

如何设置我的用户实体类来加载User::$roles 属性,以便Symfony 可以使用User::getRoles() 函数检索它们?最好通过 Role 实体的加载和数组。

相当于这个:

SELECT r.* 
FROM user u 
   LEFT JOIN role r 
   ON (u.role & r.permission) 
WHERE u.id = :id

【问题讨论】:

  • 位字段是一种可怕的数据存储方式,尤其是因为掩码是不可分割的(索引是基于完整值的 B 树,而不是单个位)并且无法强制执行引用完整性。如果您绝对必须这样做,那么至少考虑 MySQL 的 SET 数据类型(它作为表面下的位字段实现,但提供了一个人性化的 API,通过该 API 可以通过名称;也可以在连接条件中使用FIND_IN_SET())。

标签: php mysql symfony doctrine-orm


【解决方案1】:

角色可以存储在某个类中,例如(将下面的代码视为伪代码,因为):

class Roles 
{
    static private $roles = array(
        'ROLE_ADMIN',
        'ROLE_DEV'
    );

    public static function getRoleName($index)
    {
        return (isset($roles[$value]) ? $roles[$value] : false);
    }

    public static function getIndex($value)
    {
        return array_search($value, $roles);
    }
}

如果您需要,可以从数据库中的某个地方生成它(查看学说中的生命周期事件)

然后您可以定义您的自定义映射原则类型让我们说“角色” Custom mapping types

类似这样的东西(未经测试,您必须进行一些检查以不溢出整数大小):

class RoleType extends Type
{
    const ROLE_TYPE = 'role'; 

    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        return 'INT'; //your sql type
    }

    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        // ensure to requrie your role class in bootstrap
        $roles = array();
        $index = 0;
        while ($value) {
           $role = $value & 1;
           if ($role && $roleName = Roles::getRoleName($index)) {
               $roles[] = $roleName;
           }
           if ($roleName === false) {
             break;
           }

           $value = $value >> 2;
           ++$index;
        }

        return $roles;
    }

    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        $roleValue = 0;
        foreach ($value as $roleName) {
            $role = Roles::getIndex($roleName);
            if ($role !== false) {
                $roleValue |= pow(2, $role);
            }
        }

        return $roleValue;
    }

    public function getName()
    {
        return self::ROLE_TYPE;
    }
}

并在 Symfony 中注册类型Registering Custom Mapping Types

无论如何,我认为最好的选择是在用户和角色之间建立关系。

【讨论】:

    猜你喜欢
    • 2014-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    相关资源
    最近更新 更多