简体   繁体   English

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

[英]Symfony2 - Get an entity instead of PersistentCollection in twig

I'm using symfony2, and I can't manage to get my related entity in twig. 我正在使用symfony2,我无法设法让我的相关实体在树枝上。

So I have my main entity, let's call it Post, which has a OneToMany relation : 所以我有我的主要实体,我们称之为Post,它具有OneToMany关系:

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

And I'm passing it to twig with my controller, I can access every property, but when I try to access a property with relations like "Comment", i'm getting a "Doctrine\\ORM\\PersistentCollection)" which has a lot of private property, and I can't manage to get the properties of this related entity... 而且我用控制器将它传递给twig,我可以访问每个属性,但是当我尝试访问像“Comment”这样的关系的属性时,我得到的是一个“Doctrine \\ ORM \\ PersistentCollection” ,它有很多私有财产,我无法设法获得这个相关实体的属性...

I'm a little confused, and I don't know what I'm doing wrong... 我有点困惑,我不知道我做错了什么......

Get First item of the doctrine collection in twig 在树枝上获取第一项教义集

if you have only 1 object on the collection then you can get it by using the first method 如果集合中只有一个对象,那么可以使用first一种方法获取它

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

PersistentCollection: first() method PersistentCollection:first()方法

Convert DoctrineCollection to array in twig 将DoctrineCollection转换为twig中的数组

To convert the doctrine collection to an array you can use the getValues() method : 要将doctrine集合转换为数组,可以使用getValues()方法:

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

PersistentCollection: getValues() method PersistentCollection:getValues()方法

It's because you are trying to access a collection of entities directly. 这是因为您试图直接访问实体集合。 You have to loop your comments collection : 你必须循环你的评论集合:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM