Return array, not object from Doctrine query - Symfony2

放肆的年华 提交于 2020-06-10 02:25:06

问题


I'm using this:

$this->getDoctrine()->getRepository('MyBundle:MyEntity')->findAll(array(), Query::HYDRATE_ARRAY);

I thought that should ensure it returns an array of an array, but it still returns an array of objects.

I need the whole result returned as an array of an array so I can do this kind of thing (silly example, but it explains what I mean):

<?php
$result = $this->getDoctrine()->getRepository('MyBundle:MyEntity')->findAll('return-an-array');
?>    
This is the age of the person at the 5th record: <?php echo $result[4]['age']; ?>

回答1:


According to this EntityRepository class, findAll don't take multiple arguments.

The code below should do what you want

$result = $this->getDoctrine()
               ->getRepository('MyBundle:MyEntity')
               ->createQueryBuilder('e')
               ->select('e')
               ->getQuery()
               ->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);



回答2:


You can also use the getArrayResult() function instead of getResult(). It returns an array of data instead:

$query = $em->createQuery("SELECT test FROM namespaceTestBundle:Test test");
$tests = $query->getArrayResult();



回答3:


Use getScalarResult() to get an array result with objects truncated to strings.



来源:https://stackoverflow.com/questions/17498637/return-array-not-object-from-doctrine-query-symfony2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!