简体   繁体   English

如何遍历symfony(Doctrine)结果对象

[英]How to iterate through a symfony (Doctrine) result object

I have the following query: 我有以下查询:

function indexAction()
{
    $u = $this->getDoctrine()->getRepository("AppBundle:Users")->findAll( \Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY );

    return $this->render("default/test.html.twig", ["users" => $u]);
}

And I loop through it in Twig Template with this loop: 我通过以下循环在Twig模板中循环浏览:

{%  for item in users %}
<li>{{ item.email }} : </li>
{%  endfor %}

And I encounter this error: 我遇到这个错误:

Impossible to access a key "name" on an object of class "AppBundle\Entity\Users" that does not implement ArrayAccess interface in default/test.html.twig at line

Something is wrong. 出了点问题。 You pass users variable to the template, but you are using myItems in the for loop. 您将users变量传递给模板,但是您正在for循环中使用myItems

Try this: 尝试这个:

{% for item in users %}
    {{ dump(item) }}<br />
{% endfor %}

Does your class implements ArrayAccess in your entity definition ? 您的类在您的实体定义中实现ArrayAccess吗?

class Foo implements ArrayAccess

You will have to add several methods in your class for this to work : 您必须在您的类中添加几个方法,以使其正常工作:

To implement ArrayAccess you need to implement four methods: offsetExists, offsetGet, offsetSet and offsetUnset. 要实现ArrayAccess,您需要实现四个方法:offsetExists,offsetGet,offsetSet和offsetUnset。 ArrayAccess::offsetExists must return a boolean, offsetGet can return any valid PHP type while offsetSet and offsetUnset should not return any value. ArrayAccess :: offsetExists必须返回一个布尔值,offsetGet可以返回任何有效的PHP类型,而offsetSet和offsetUnset不应返回任何值。 Once you implement these methods you can treat an object as if it is an array for the purposes of saving and retrieving properties 一旦实现了这些方法,就可以将对象当作数组来对待,以保存和检索属性。

More details here . 更多细节在这里

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

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