我可以在 Doctrine2 中迭代实体的属性吗?
我使用
$myblogrepo = $this->_doctrine->getRepository('Entities\Blog')->findBy(array('id' => 12);
我访问通过
foreach($myblogrepo as $key =>$value){
echo $key . $value;
}
如何获取字段名称?我认为关键=>可以工作,但它把密钥打印为 0
所以我认为这会工作:
foreach($myblogrepo[0] as $key =>$value){
echo $key . $value;
}
但仍然没有.. }
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..
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的博客实体的属性很可能被声明为
受保护
。这就是为什么您无法从实体本身外部迭代它们的原因。如果您以只读方式使用博客实体,并且只需要访问标记为@Columns的属性(阅读:您不需要在实体上调用任何方法),您可以考虑使用数组水合。这样您将处理简单的数组,并且
$k=>$v
类型迭代将正常工作。否则,您需要在实体类上创建某种 getValues() 方法。这可能是一个简单的实现,只需构建数组并返回它。
最后,您可以创建一个通用的 getValues() 作为实用函数,它使用原则的类元数据来找出列和实体具有哪些数据,并对这些数据进行操作。像这样的简单实现:
编辑 - 上述方法的更成熟版本似乎是可在此处获取 - 我还没有使用过它,但它看起来很有希望。
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:
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.
如果您只需要以快速且简单的方式获取实体的属性,这就是我在项目中所做的:
我的所有实体都继承自 EntityBase 类,该类具有以下方法:
所以我所要做的就是调用
$entity->toValueObject()
并且我获得了一个标准对象,其中实体的所有属性都作为公共属性。If you just need to get the properties of the entity in a fast and easy way, this is what I do in my projects:
All my entities inherit from an EntityBase class, which has the following method:
So all I have to do is call
$entity->toValueObject()
and I obtain a standard object with all of the entity's properties as public properties.使用
findOneBy
而不是findBy
来选择单行。您的键是
0
因为它是可能的多行结果中的第一行。Use
findOneBy
instead offindBy
to select a single row.Your key was
0
because it was the first row in a possible multi-row result.这是我对序列化器类的实现,它还检查它是否是一个学说实体:
This is a my implementation of a serializer class that also check if it is a doctrine entity: