dean jase dean jase - 28 days ago 8x
PHP Question

Can I iterate over an Entity's properties in Doctrine2?

i use

$myblogrepo = $this->_doctrine->getRepository('Entities\Blog')->findBy(array('id' => 12);

i access via

foreach($myblogrepo as $key =>$value){

echo $key . $value;


how can i get the field names? i thought the key => would work but it print s the key as 0

so i thought this would work:

foreach($myblogrepo[0] as $key =>$value){

echo $key . $value;

but still nothing..


In all likelihood, your Blog entity's properties are declared as protected. This is why you can't iterate over them from outside the the Entity itself.

If you're using your Blog entities in a read-only fashion, and only need access to the properties marked as @Columns (read: you don't need to call any methods on your entity), you might consider using array-hydration. That way you'll be dealing with simple arrays, and $k=>$v type iteration will work fine.

Otherwise, you'll need to create some kind of getValues() method on your entity class. This could be a simple implementation that just builds and array and returns it.

Finally, you could create a general-purpose getValues() as a utility function that uses doctrine's class metadata to figure out what columns and entity has, and operate on those data. A simple implementation like this:

function getEntityColumnValues($entity,$em){
  $cols = $em->getClassMetadata(get_class($entity))->getColumnNames();
  $values = array();
  foreach($cols as $col){
    $getter = 'get'.ucfirst($col);
    $values[$col] = $entity->$getter();
  return $values;

EDIT - A more mature version of the above method seems to be available here - I've not played with it yet, but it looks promising.