How to return object from a DQL query?
Asked Answered
H

3

5

I have written 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();

Currently it returns the results of the query in an array like so:

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 pretty sure the previous version of Doctrine returned objects by default).

I tried:

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

But that didn't make a difference.

Appreciate the help

Hanfurd answered 15/8, 2011 at 10:29 Comment(0)
G
6

You are fetching only position column from DB. Try replacing select('r.position') with select(r). See DQL reference

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

Galicia answered 15/8, 2011 at 10:42 Comment(0)
L
3

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

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

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

Lumpy answered 13/4, 2014 at 18:12 Comment(0)
S
1

I could not solve my problem with your solution, here my part 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)
 }
}

thx for any help

Shoulders answered 18/11, 2013 at 12:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.