DoctrineCollection: difference between toArray() and getData()
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.)
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)