Return array, not object from Doctrine query - Sym

2020-06-08 03:23发布

问题:

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.