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

5

11

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?

Unwholesome answered 20/3, 2017 at 17:51 Comment(0)
B
26

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);
Beaumarchais answered 20/3, 2017 at 21:2 Comment(3)
thanks man, but i got an argument exception for createQueryBuilder(),after i pass the argument('c'), i am getting results. even $query->getArrayResult() also gives the same resultsUnwholesome
Sorry for that. In fact I forgot to pass the alias to the createQueryBuilder() method. I fixed my answer.Beaumarchais
You also have to add use Doctrine\ORM\Query;Metallography
I
9

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

doctrine hydration modes

Inessential answered 24/4, 2018 at 16:12 Comment(1)
Much better way and avoiding importing more classesMerrie
C
1

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);
Concussion answered 21/3, 2017 at 2:46 Comment(0)
I
-1

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);
Ibanez answered 11/7, 2022 at 10:8 Comment(0)
F
-2

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.

Fitment answered 22/2, 2019 at 14:20 Comment(3)
Please add some explanation to your code - why should one use that? Keep in mind that others should be able to learn from that codeJudah
Added a little explanation. :) thanks for the commentHarbird
Hydration is costly. Do not hydrate your objects if you only want arrays.Ebba

© 2022 - 2024 — McMap. All rights reserved.