簡體   English   中英

Symfony2 - 在樹枝中獲取實體而不是PersistentCollection

[英]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 %}

PersistentCollection: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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM