Search code examples
phpdoctrinedoctrine-collection

DoctrineCollection: difference between toArray() and getData()


Basically, if I had a DoctrineCollection of DoctrineRecord objects, and wanted to convert it to an array, I could use:

$collection->toArray() or $collection->getData()

But I don't understand what's the difference between this two methods.


Solution

  • Update: See response below for Doctrine 2. This response only covers Doctrine 1

    ->toArray()
    

    Most programmers would probably assume that calling toArray() on the collection would simply place all the objects into an array. While toArray() does do that, it also converts the objects themselves into associative arrays, which is likely not what you want.

    toArray() is equivalent to this

    $q = Doctrine_Query::create()
       ->from('Post p')
       ->setHydrationMode(Doctrine::HYDRATE_ARRAY);
    
    
    $resultSet = $q->execute(); // $resultSet is an array
    

    according to the documentation

    foreach ($resultSet as $post) {
        // $post is an array
        echo $post['title'];
    }
    

    so each element of the array is also an array associative.

    Instead:

    ->getData()
    

    Not exactly the most intuitive name, getData() actually takes all the objects in the Doctrine Collection object and places them into an array – without altering the objects themselves.

    so you will get objects!

    foreach ($resultSet as $post) {
            // $post is not an array
            echo $post->Id;
        }
    

    source: here

    Keep in mind this only works for Doctrine 1, for Doctrine 2 see answer below (or comments)