开发者

How to get a Doctrine2 result object as an associative array?

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 arr开发者_JAVA技巧ay 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.


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 hydrations Doctrine\ORM\Query::HYDRATE_ARRAY.

$accounts = $qb->getQuery()->getResult( Doctrine\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:

 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 Docs: http://www.doctrine-project.org/api/orm/2.1/namespace-Doctrine.ORM.Internal.Hydration.html


You can also use getArrayResult() as a shortcut to passing in the constant to get an array back:

$accounts = $qb->getQuery()->getArrayResult();


You should use constant containing value 2 and it is inbuilt, you can do it like this at the end part of your query

$qb->getQuery()->getResult( Doctrine\ORM\Query::HYDRATE_ARRAY );


$data = $this->entity->findOneBy(array('key' => $value));

$hydrator = new \DoctrineModule\Stdlib\Hydrator\DoctrineObject($this->_em, $entity_name);

$array = $hydrator->extract($data);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜