Symfony2 - 在树枝中获取实体而不是PersistentCollection

Kaz*_*Kaz 6 php symfony doctrine-orm

我是symfony2的初学者,我无法设法让我的相关实体在树枝上.

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

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

而且我用控制器将它传递给twig,我可以访问每个属性,但是当我尝试访问像"Comment"这样的关系的属性时,我得到的是一个 "Doctrine\ORM\PersistentCollection" ,它有很多私有财产,我无法设法获得这个相关实体的属性...

我有点困惑,我不知道我做错了什么......

Moh*_*nda 9

在树枝上获取第一项教义集

如果集合中只有一个对象,那么可以使用该first方法获取它

{% set comment = post.comments.first %}
Run Code Online (Sandbox Code Playgroud)

PersistentCollection:first()方法

将DoctrineCollection转换为twig中的数组

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

{% set arrayComment = post.comments.getValues %}
Run Code Online (Sandbox Code Playgroud)

PersistentCollection:getValues()方法


Fid*_*kaj 5

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

{% for comment in post.comments %}
    // You can get your comment entity here 
    // for example
    <p>{{comment.description}}</p>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)