Hari
Hari

Reputation: 1623

How to get Array Results in findAll() - Doctrine?

I need to fetch all records in database as Array using findAll() in Doctrine, My Query is Something like this

$result = $this->getDoctrine()
                ->getRepository('CoreBundle:Categories')
                ->findAll(\Doctrine\ORM\Query::HYDRATE_ARRAY);

even if set Hydration Mode to HYDRATE_ARRAY, am getting results as objects

array:4 [▼
0 => Categories {#323 ▶}
1 => Categories {#326 ▶}
2 => Categories {#329 ▶}
3 => Categories {#332 ▶}
]

what mistake i made?

Upvotes: 11

Views: 41672

Answers (5)

b126
b126

Reputation: 1254

Sorry, I wake up this old topic after years but I find the solution offered by JMS Serializer very elegant to convert arrays of Doctrine objects into associative arrays (e.g. JSON) without having to cutomize/rewrite your repositories findAll() methods.

I think it might help some people here since JMS is a lightweight framework that is really easy to configure.

The code snippet to use will look like this:

     $serializer = SerializerBuilder::create()->build();
     $employees = getEmployeeRepo->findAll();
     $arrEmployees = $serializer->toArray($employees);

Upvotes: -1

xabbuh
xabbuh

Reputation: 5881

The findAll() method does not have any parameters. You can, for example, use the repository's createQueryBuilder() method to achieve what you want to do:

use Doctrine\ORM\Query;

// ...

$query = $this->getDoctrine()
    ->getRepository('CoreBundle:Categories')
    ->createQueryBuilder('c')
    ->getQuery();
$result = $query->getResult(Query::HYDRATE_ARRAY);

Upvotes: 26

Andrei L. Nvê.
Andrei L. Nvê.

Reputation: 1

I have made this function:

https://gist.github.com/AndreiLN/3708ab829c26cee4711b1df551d1385f

/** 
 * Converte um objeto Doctrine para um array
 * @param $dados
 * @param $single define se é uma única execução (Sem recursividade)
 * @return array
*/
public function doctrine_to_array($data, $single = false) {
    if (is_object($data)) { // Verifica se é array ou objeto
        $methods = get_class_methods($data);
        $methods = array_filter($methods, function($val){ return preg_match('/^get/', $val); });

        $return = [];
        if(count($methods)){
            foreach($methods as $method){
                $prop = lcfirst(preg_replace('/^get/', "", $method));
                $val = $data->$method();

                if(!$single){
                    $return[$prop] = $this->doctrine_to_array($val, $single);
                } else {
                    if(!is_array($val) && !is_object($val)){
                        $return[$prop] = $val;
                    }
                }
            }
        }
        return $return;
    } else if(is_array($data)){
        if(count($data)){
            foreach($data as $idx => $val){
                $data[$idx] = $this->doctrine_to_array($val, $single);
            }
        }
    }
    return $data; // Retorna o próprio valor se não for objeto
}

If you find some upgrade please let me know.

Explaining more of this function: it's get the doctrine object of array, if it's a object it's reads all get's methods to get all values, if this values is another doctrine object (And single option is not set) it's call the function recursively until it's done. If the parameter is a array the function will go throught of it and call the method again for all it's values.

It's easy to use, but not tested in all situations.

Upvotes: -2

Pascal KOCH
Pascal KOCH

Reputation: 129

It's possible to use $query->getArrayResult() as a shortcut to $query->getResult(Query::HYDRATE_ARRAY)

doctrine hydration modes

Upvotes: 10

yang
yang

Reputation: 183

The format in which the result of a DQL SELECT query is returned can be influenced by a so-called hydration mode so you couldn't use it for findAll().you may try this below:

$em = $this->getDoctrine()->getManager();
$result = $em->createQuery('select m from CoreBundle:Categories m')
        ->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);

Upvotes: 1

Related Questions