Symfony 使用 Roles 存储库的哪种方法来加载 Roles 实体

Which method of Roles repository Symfony uses to load Roles entity

我根据 Symfony 安全章节在数据库中加载了我的用户和角色。用户实现 AdvancedUserInterface, \Serializable, 角色实现 RoleInterface。 我的角色实体:

AppBundle\Entity\Roles:
   type:     entity
   table:     Roles
   repositoryClass: AppBundle\Repository\Roles
[...]
     oneToMany:
          users:
               targetEntity:     Users
               mappedBy:          role
               cascade:           [persist]
          privs:
               targetEntity:     RolesPrivileges
               mappedBy:          role
               cascade:           [persist]

我的 RolesPrivileges 实体与 Roles 建立了多对一关系,并且与 Privileges 建立了同类关系:

AppBundle\Entity\RolesPrivileges:
     type:     entity
     table:     RolesPrivileges
     repositoryClass: AppBundle\Repository\RolesPrivileges
id:
    role:
           associationKey: true
           type:     integer
    privilege:
           type:     integer
           associationKey: true
 fields:
    related:
           type:     boolean
           nullable:   FALSE
           options:
                  default:    0
 manyToOne:
      role:
           targetEntity:     Roles
           inversedBy:      privs
           joinColumn:
                name:     role_id
                referencedColumnName:     id
      privilege:
           targetEntity:     Privileges
           joinColumn:
                name:     privilege_id
                referencedColumnName:     id

最后是特权实体:

AppBundle\Entity\Privileges:
     type:     entity
         table:     Privileges
         id:
[...]

       fields:
           short:
               type:     string
               length:    50
               nullable:    FALSE

我这样写是为了能够检查 Controller 中每个操作的详细访问权限(登录用户的)。我只是遍历与分配给用户的角色相关的权限。

问题是 Symfony 正在为来自特权 table 的每个条目分别查询数据库。我通过使用查询获取所有内容并将其存储在受保护的变量中来在控制器中修复它。

但我不知道如何解决我从 twig 模板(使用 Roles 实体中定义的方法)遍历权限时出现的相同问题。我在想我可以重新定义 RolesRepository 中的一种方法,以便能够在一个查询中获取所有权限。我该怎么做?

这些关系在 Doctrine 中默认是延迟加载的。如果您总是希望在获取权限时随角色一起加载权限,请将关系的加载类型配置为 EAGER。

Whenever you query for an entity that has persistent associations and these associations are mapped as EAGER, they will automatically be loaded together with the entity being queried and is thus immediately available to your application.

http://doctrine-orm.readthedocs.org/en/latest/reference/working-with-objects.html#by-eager-loading

AppBundle\Entity\Roles:
    oneToMany:
        [...]
        privs:
            [...]
            fetch: EAGER

AppBundle\Entity\RolesPrivileges:
    [...]
    manyToOne:
        privilege:
            [...]
            fetch: EAGER