如何以关联数组的形式获取 Doctrine2 结果对象?
我有一个简单的实体,它是一个保存用户数据的表 我想将特定用户的所有列作为数组获取,然后对它们进行 json_encode,但我得到的是一个实体对象,我必须对每个值使用 get 方法。我只想要一个用户表值的关联数组。 我尝试过但不起作用的代码(返回实体对象)如下: 1.
$qb = $this->em->createQueryBuilder();
$qb->add('select', 'a')
->add('from', 'Entities\Adminprofile a')
->add('where', 'a.userid = 3333');
$accounts = $qb->getQuery()->getResult();
2.
$account = $this->em->getRepository('Entities\Adminprofile')->findOneBy(
array('userid' => '3333'));
PS:我使用的是z2d2项目,该项目是将doctrine2集成到Zend框架中。
I have a simple entity which is a table holding my user data
and I want to fetch all columns of a specific user as an array and then json_encode them but what I get is an entity object which I will have to use get method for every value. I just want an associative array of my user table values.
The codes I tried and didn't work (returned entity object) are as follows:
1.
$qb = $this->em->createQueryBuilder();
$qb->add('select', 'a')
->add('from', 'Entities\Adminprofile a')
->add('where', 'a.userid = 3333');
$accounts = $qb->getQuery()->getResult();
2.
$account = $this->em->getRepository('Entities\Adminprofile')->findOneBy(
array('userid' => '3333'));
PS: im using z2d2 Project,which is doctrine2 integration into Zend framework.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当您执行
$accounts = $qb->getQuery()->getResult();
时,您传递给 getResult 的参数告诉它如何合并将返回的结果集。数组水合
如果你想要数组,那么你应该为数组水合
Doctrine\ORM\Query::HYDRATE_ARRAY
传递CONSTANT
。如果您使用
findOneBy()
,那么它将始终返回一个实体。由于 find 工作原理的内部原因,除了返回实体之外,您不能通过任何其他方式告诉它进行水合。在这种情况下,您需要做的是在实体内部创建一个
getValues()
方法,该方法返回实体的数组,如下所示:Hydration API 文档:http://www.doctrine-project.org/api/orm/ 2.1/命名空间-Doctrine.ORM.Internal.Hydration.html
When you do
$accounts = $qb->getQuery()->getResult();
the argument you pass to getResult tells it how to hydrate the result set which is will return.Array Hydration
If you want arrays, than you should pass the
CONSTANT
for array hydrationsDoctrine\ORM\Query::HYDRATE_ARRAY
.If you are using
findOneBy()
then it will always return an entity. Due to the internals of how find works, you cannot tell it to hydrate by any other means other than to return entities.In this scenario, what you need to do is create a
getValues()
method inside of your entity which returns an array of your entity, like this:Hydration API Docs: http://www.doctrine-project.org/api/orm/2.1/namespace-Doctrine.ORM.Internal.Hydration.html
您还可以使用 getArrayResult() 作为传入常量以获取数组的快捷方式:
You can also use getArrayResult() as a shortcut to passing in the constant to get an array back:
您应该使用包含值 2 的常量,它是内置的,您可以在查询的末尾部分这样做
You should use constant containing value 2 and it is inbuilt, you can do it like this at the end part of your query