2017-01-12 55 views
1

在我的应用程序,我有用户。 每个用户都有一个角色(管理员,测试仪,...) 每个角色可以有多个权限(主页视图,contactpage视...)选择实体限制与许多关系的深度

所以,我有一个多对多的关系

因为我想从角色的权限和权限中获得角色,我有双向关系。

我想要的仅仅是选择其角色

我的问题一个权限:当我得到许可,它就会用它与它的角色的权限的每个角色......

结果开始例如:

{ 
    "id": 4, 
    "nom": "Accès au backoffice", 
    "slug": "page-backoffice", 
    "role": [ 
    { 
     "id": 1, 
     "libelle": "Administrateur", 
     "permission": [ 
     { 
      "id": 3, 
      "nom": "Visualisation du stock global", 
      "slug": "page-visu-stock-global", 
      "role": [ 
      { 
       "id": 2, 
       "libelle": "Responsable d'exploitation", 
       "permission": [ 
       { 
        ....... 

我要的是:

{ 
    "id": 4, 
    "nom": "Accès au backoffice", 
    "slug": "page-backoffice", 
    "role": [ 
    { 
     "id": 1, 
     "libelle": "Administrateur", 
     "slug": "administrateur" 
    }, 
    { 
     "id": 2, 
     "libelle": "Responsable d'exploitation", 
     "slug": "responsable-exploitation" 
    }, 
    .... 

哪有我做到了吗?

我的ORM文件关联信息: Permissions.orm.yml:

manyToMany: 
    role: 
     targetEntity: Role 
     cascade: { } 
     fetch: LAZY 
     mappedBy: permission 
     inversedBy: null 
     joinTable: null 
     orderBy: null 

role.orm.yml:

manyToMany: 
    permission: 
     targetEntity: Permissions 
     cascade: { } 
     fetch: LAZY 
     mappedBy: null 
     inversedBy: role 
     joinTable: 
      name: role_permission 
      joinColumns: 
       - 
        name: role_id 
        referencedColumnName: id 
      inverseJoinColumns: 
       - 
        name: permission_id 
        referencedColumnName: id 
     orderBy: null 

感谢您的帮助

+1

你应该看看的[序列化基团](https://symfony.com/doc/current/components/serializer.html#component-serializer-attributes-groups )和[如何启用它们](https://symfony.com/doc/current/serializer.html#using-serialization-groups-annotations)。希望它可以帮助你 – OlivierC

+0

使用序列化不会阻止教条获取数据做循环权限>角色>权限>角色...我错了吗? –

+0

只有在需要数据时,您才会进行懒读取以获取happend。事实是,你提交了你的对象作为一个JSON,我认为它被序列化为一个API – OlivierC

回答

1

晴你不希望将您的实体一次曝光到您的api中,尤其是在将相关实体暴露给其他实体时。

序列化组允许你选择你想在api中公开哪些属性。通过这种方式,您可以避免在公开相关实体时(如暴露其权限的角色暴露其角色,将其权限暴露给无限以及更远的用户)进入深层。

Symfony有关于what are serialization groupshow to enable and use serialization groups的一些文档。

-1

这里是如何做到这一点的例子:

use JMS\Serializer\Annotation\MaxDepth; 

class User 
{ 
    private $username; 

    /** @MaxDepth(1) */ 
    private $friends; 

    /** @MaxDepth(2) */ 
    private $posts; 
} 

class Post 
{ 
    private $title; 

    private $author; 
} 

而对于控制器:

use JMS\Serializer\SerializationContext; 

$serializer->serialize($data, 'json', SerializationContext::create()->enableMaxDepthChecks()); 

注有序列化过程中大约20注解关键字“过滤器”的数据。

示例源:

http://jmsyst.com/libs/serializer/master/cookbook/exclusion_strategies#limiting-serialization-depth-of-some-properties

+0

尽管此链接可能回答此问题,但最好在此处包含答案的重要部分并提供供参考的链接。如果链接页面更改,则仅链接答案可能会失效。 - [来自评论](/ review/low-quality-posts/18441824) – Jobin