我可以在 Doctrine2 中迭代实体的属性吗?
我用
$myblogrepo = $this->_doctrine->getRepository('EntitiesBlog')->findBy(array('id' => 12);
我通过
foreach($myblogrepo as $key =>$value){
echo $key . $value;
}
如何获取字段名称?我认为 key => 会起作用,但它会将 key 打印为 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 实体的属性被声明为 protected
.这就是为什么你不能从实体本身之外迭代它们.
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.
如果您以只读方式使用博客实体,并且只需要访问标记为 @Columns 的属性(阅读:您不需要调用实体上的任何方法),您可以考虑使用阵列水合.这样你就可以处理简单的数组,并且 $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() 作为实用函数,它使用学说的类元数据来确定哪些列和实体具有,并对这些数据进行操作.像这样的简单实现:
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 - 上述方法的一个更成熟的版本似乎是 在此处可用 - 我还没有玩过它,但它看起来很有希望.
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.
相关文章