我可以在Doctrine2中遍历实体的属性吗? [英] Can I iterate over an Entity's properties in Doctrine2?
问题描述
我使用
$myblogrepo = $this->_doctrine->getRepository('Entities\Blog')->findBy(array('id' => 12);
我通过
foreach($myblogrepo as $key =>$value){
echo $key . $value;
}
我如何获得字段名称? key =>可以工作,但是它将s的密钥打印为0
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.. }
推荐答案
您的Blog实体的属性很可能被声明为受保护的
,这就是为什么您不能从实体本身。
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.
如果您以只读方式使用Blog实体,并且只需要访问标记为@Columns的属性(读:yo您不需要在您的实体上调用任何方法),则可以考虑使用数组水化。这样,您将处理简单的数组,并且 $ k => $ v
类型迭代将可以正常工作。
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.
否则,您将需要在实体类上创建某种getValues()方法。
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.
最后,您可以创建一个通用的getValues()作为使用doctrine类的实用函数。元数据以找出列和实体具有什么,并对这些数据进行操作。像这样的简单实现:
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.
这篇关于我可以在Doctrine2中遍历实体的属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!