0

我有 2 个实体:用户、文章和与属性的多对多关系,用于描述用户与文章的交互。该属性描述了交互的类型(例如,书签...)。

在这种情况下,我需要一个中间实体(UserArticle),它具有从 Article 到 UserArticle 的一对多关系:该属性在 Article 实体中称为 userInteractions。

它是一个 API,当我创建查询生成器时,我会得到当前登录用户喜欢和收藏的文章的这种结果:

//Article Json Object
{ 
       ...
       userInteractions : [
         {
            "type": "like"
         },
         {
            "type": "bookmark"
         }
       ]

}

没关系,但对 javascript 前端不方便:我更愿意公开布尔字段:isLiked:true、书签:true、otheraction:false ...,因为它更容易解析。

我想我必须写一个定制的水合器。我为另一种关系(没有属性的多对多)做了它,它就像一个魅力,但在这种情况下,它只有在有 0 个或一个交互时才有效。如果有 2 个或更多操作,我会在调用父 Doctrine Object hydrator 时收到 500 错误和通知。这是我的保湿剂:

class ArticleHydrator extends ObjectHydrator {
  protected function hydrateRowData(array $data, array &$result)
  {

    $hydratedResult = [];
    parent::hydrateRowData($data, $hydratedResult);
    //this call generates a notice Undefined offset: 0 at line 525 of    doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php

    $article->setUserInteractionsFlags(); 
    // works with less than 2 interactions in the left join and correctly hydrates the not-persisted booleans added to Article entity
 }

}

我试图查看对象水合器,但它确实是一团糟,不容易理解,我认为在这种情况下,使用自定义水合器可能是不合适的。有什么建议吗?谢谢

4

1 回答 1

0

如果您想使用 JMS 序列化程序公开该属性只是为了使消费客户端更容易读取(尤其是不希望写回该属性,但 OP 没有给出这个方向的提示):

只需使用虚拟属性

 /**      @Serializer\VirtualProperty()      
@JMS\SerializedName("user_interaction_flags")    */

 public function getInteractionFlags() 
 {
     return array("like" => $this->...);
 }

如果您不需要它们,您甚至可以将“原始”属性排除在序列化之外。

于 2018-04-16T21:42:29.523 回答