如何将 Doctrine2 结果对象作为关联数组获取? [英] How to get a Doctrine2 result object as an associative array?

查看:21
本文介绍了如何将 Doctrine2 结果对象作为关联数组获取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的实体,它是一个保存我的用户数据的表我想将特定用户的所有列作为数组获取,然后对它们进行 json_encode 但我得到的是一个实体对象,我必须对每个值使用 get 方法.我只想要我的用户表值的关联数组.我试过但不起作用的代码(返回的实体对象)如下:1.

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', 'EntitiesAdminprofile a')
->add('where', 'a.userid = 3333');
$accounts = $qb->getQuery()->getResult();

2.

$account = $this->em->getRepository('EntitiesAdminprofile')->findOneBy(
array('userid' => '3333'));

PS:我正在使用 z2d2 项目,它是 Dotct2 集成到 Zend 框架中.

PS: im using z2d2 Project,which is doctrine2 integration into Zend framework.

推荐答案

当你做 $accounts = $qb->getQuery()->getResult(); 你传递给的参数getResult 告诉它如何对将返回的结果集进行水合.

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.

阵列水化

如果你想要数组,那么你应该通过 CONSTANT 为数组水化DoctrineORMQuery::HYDRATE_ARRAY.

If you want arrays, than you should pass the CONSTANT for array hydrations DoctrineORMQuery::HYDRATE_ARRAY.

$accounts = $qb->getQuery()->getResult(DoctrineORMQuery::HYDRATE_ARRAY);

$accounts = $qb->getQuery()->getResult( DoctrineORMQuery::HYDRATE_ARRAY );

如果您使用 findOneBy() 那么它会总是返回一个实体.由于 find 工作原理的内部结构,除了返回实体之外,您不能通过任何其他方式告诉它水合物.

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.

在这种情况下,您需要做的是在实体内部创建一个 getValues() 方法,该方法返回实体的数组,如下所示:

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:

 public function getSimpleValues(){
     return array(
        'id'      => $this->getId(),
        'lft'     => $this->getLft(),
        'rgt'     => $this->getRgt(),
        'name'    => $this->getName(),
        'md5Name' => $this->getMd5Name(),              
        'owner'   => $this->getOwner()->getId(),
        'etag'    => $this->getEtag()
    );
}

Hydration API 文档:http://www.doctrine-project.org/api/orm/2.1/namespace-Doctrine.ORM.Internal.Hydration.html

Hydration API Docs: http://www.doctrine-project.org/api/orm/2.1/namespace-Doctrine.ORM.Internal.Hydration.html

这篇关于如何将 Doctrine2 结果对象作为关联数组获取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆