Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 358
NadiaFaya Avatar asked Sep 13 '13 13:09

NadiaFaya


2 Answers

Just an update for Doctrine 2:

->getData()

has become

->getValues()

Gonzalo was right for Doctrine 1, but hopefully this helps anyone who also found this thread looking for an answer but encountered problems using getData().

(Sorry Gonzalo, I don't have the reputation score yet to comment.)

like image 135
fridde Avatar answered Nov 05 '22 13:11

fridde


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)

like image 25
Gonzalo.- Avatar answered Nov 05 '22 13:11

Gonzalo.-