[英]Symfony2 - Get an entity instead of PersistentCollection in twig
我正在使用symfony2,我無法設法讓我的相關實體在樹枝上。
所以我有我的主要實體,我們稱之為Post,它具有OneToMany關系:
/**
* @ORM\OneToMany(targetEntity="Comment", mappedBy="Post", cascade={"persist", "remove"})
*/
private $comments;
而且我用控制器將它傳遞給twig,我可以訪問每個屬性,但是當我嘗試訪問像“Comment”這樣的關系的屬性時,我得到的是一個“Doctrine \\ ORM \\ PersistentCollection” ,它有很多私有財產,我無法設法獲得這個相關實體的屬性...
我有點困惑,我不知道我做錯了什么......
在樹枝上獲取第一項教義集
如果集合中只有一個對象,那么可以使用first
一種方法獲取它
{% set comment = post.comments.first %}
PersistentCollection:first()方法
將DoctrineCollection轉換為twig中的數組
要將doctrine集合轉換為數組,可以使用getValues()方法:
{% set arrayComment = post.comments.getValues %}
這是因為您試圖直接訪問實體集合。 你必須循環你的評論集合:
{% 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.