【问题标题】:Symfony2 - Get an entity instead of PersistentCollection in twigSymfony2 - 在树枝中获取实体而不是 PersistentCollection
【发布时间】:2014-07-09 09:01:48
【问题描述】:

我正在使用 symfony2,但无法在 twig 中获取相关实体。

所以我有我的主要实体,我们称之为 Post,它有一个 OneToMany 关系:

/**
 * @ORM\OneToMany(targetEntity="Comment", mappedBy="Post", cascade={"persist", "remove"})
 */
private $comments;

我用我的控制器将它传递给 twig,我可以访问每个属性,但是当我尝试访问具有“评论”等关系的属性时,我得到一个 “Doctrine\ORM\PersistentCollection )" 里面有很多私有属性,我无法获取到这个相关实体的属性...

我有点迷茫,不知道自己做错了什么……

【问题讨论】:

    标签: php symfony doctrine-orm


    【解决方案1】:

    在 twig 中获取学说集合的第一项

    如果集合中只有 1 个对象,则可以使用 first 方法获取它

    {% set comment = post.comments.first %}
    

    PersistentCollection: first() method

    将 DoctrineCollection 转换为 twig 中的数组

    要将教义集合转换为数组,您可以使用 getValues() 方法:

    {% set arrayComment = post.comments.getValues %}
    

    PersistentCollection: getValues() method

    【讨论】:

      【解决方案2】:

      这是因为您尝试直接访问实体集合。 你必须循环你的 cmets 集合:

      {% for comment in post.comments %}
          // You can get your comment entity here 
          // for example
          <p>{{comment.description}}</p>
      {% endfor %}
      

      【讨论】:

      • 好的,谢谢,让我困惑的一定是我的帖子只有 1 条评论,所以我想这就是我试图直接访问它的原因,我想需要喝杯咖啡..
      • 这在php btw中是一样的; foreach($post->getComments() as $comment) { dump($comment->getDescription()); }
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      • 2013-01-23
      • 2015-12-10
      相关资源
      最近更新 更多