繁体   English   中英

在Twig中读取PersistentCollections,就好像它们是一个数组一样

[英]Reading PersistentCollections in Twig as if they were an Array

我在两个类(协议和历史)之间存在双向的一对多关系。 在搜索特定协议时,我希望看到与该协议相关的所有历史记录条目。

在渲染模板时,我通过了以下内容:

return $this->render('FunarbeProtocoloAdminBundle:Protocolo:show.html.twig', array(
        'entity'      => $entity,
        'delete_form' => $deleteForm->createView(),
        'history' => $entity->getHistory(),
    )
);

entity->getHistory()返回一个PersistentCollection而不是一个数组,这将导致以下错误:

{% for hist in history %}
<tr>
    <td>{{ hist.dtOcorrencia|date('d/m/Y H:i') }}</td>
    <td>{{ hist.dtRetorno|date('d/m/Y H:i') }}</td>
</tr>
{% endfor %}

如果我通过$em->getRepository('MyBundle:History')->findByProtocol($entity)代替$entity->getHistory() $em->getRepository('MyBundle:History')->findByProtocol($entity) ,则可以正常工作。 但是我认为具有双向关系的主要目的是避免打开存储库并明确打开新的结果集。

难道我做错了什么? 我应该怎么做?

我要做的就是在TWIG上调用以下命令:

{% for hist in entity.history %}

没有其他答案对我有用。 我必须直接在树枝上调用该属性,而不是使用其吸气剂。 不知道为什么,但是有效。

谢谢。

尝试这个:

return $this->render('FunarbeProtocoloAdminBundle:Protocolo:show.html.twig'
    ,array(
          'entity'      => $entity,
         ,'delete_form' => $deleteForm->createView(),
         ,'history'     => $entity->getHistory()->toArray()
                                                ///////////
    )
);

您的代码很好,我总是省去麻烦,把我的收藏放到树枝上,而不是通过我的视图传递。 您也可以尝试这个。

渲染代码变更

return $this->render('FunarbeProtocoloAdminBundle:Protocolo:show.html.twig', array(
        'entity'      => $entity,
        'delete_form' => $deleteForm->createView(),
    )
);

您想直接在树枝中访问历史记录。

枝条

{% for hist in entity.getHistory() %}
    <tr>
        <td>{{ hist.dtOcorrencia|date('d/m/Y H:i') }}</td>
        <td>{{ hist.dtRetorno|date('d/m/Y H:i') }}</td>
    </tr>
{% endfor %}

如果更改后的结果相同,请尝试检查hist是否有数组,它可能是嵌套的! 永久收藏倾向于这样做...

{% for history in entity.getHistory() %}
    {% for hist in history %}
        <tr>
            <td>{{ hist.dtOcorrencia|date('d/m/Y H:i') }}</td>
            <td>{{ hist.dtRetorno|date('d/m/Y H:i') }}</td>
        </tr>
    {% endfor %}
{% endfor %}

暂无
暂无

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

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