How to return an object from a DQL query?

I wrote a DQL query in Doctrine 2:

$qb->select('r.position') ->from('\Entities\Races', 'r') ->where($qb->expr()->eq('r.entrantId', ':entrant_id')) ->setParameter('entrant_id', $this->entrantId); $query = $qb->getQuery(); $aRaces = $query->getResult(); 

It currently returns query results in an array as follows:

 Array ( [0] => Array ( [position] => 10 ) [1] => Array ( [position] => 4 ) ) 

I want the result to return an array of Races objects so that I can access the methods associated with the object (I'm sure the previous version of Doctrine returned objects by default).

I tried:

 $aRaces = $query->getResult(Query::HYDRATE_OBJECT); 

But that didn't matter.

Rate help

+4
source share
3 answers

You retrieve only the position column from the database. Try replacing select('r.position') with select(r) . See DQL Link

If you only need objects with the position attribute, refer to partial objects

+4
source

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

It returns an array with an object, and you can catch them with: $match[0];

If you want to return a single result, you should use: $qb->getOneOrNullResult()

+2
source

I could not solve my problem with your solution, here is my piece of code:

 $qb = $this->_objectManager->createQuery('Select d from Hotbed\Entity\Department d where d.id <> :id and d.title = :title'); $qb->setParameters(array('id' => $context['id'], 'title' => $value)); $match = $qb->getResult(\Doctrine\ORM\Query::HYDRATE_OBJECT); 

$ match returns this:

 array(1) { [0] => object(Hotbed\Entity\Department)#626 (4) { ['inputFilter':protected] =&gt; NULL ['id':protected] =&gt; int(25) ['title':protected] => string(4) '2222' ['state':protected] => int(0) } } 

thanks for any help

0
source

All Articles