Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 859
Mehdi Fanai Avatar asked Aug 31 '11 15:08

Mehdi Fanai


2 Answers

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

like image 100
Layke Avatar answered Nov 05 '22 17:11

Layke


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

$accounts = $qb->getQuery()->getArrayResult();
like image 26
Jeremy Hicks Avatar answered Nov 05 '22 17:11

Jeremy Hicks