Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DQL returning an array of entities instead of objects

Normally if I run a DQL query such as below it would return a list of entity objects:

$d = $this->getDoctrine()->getRepository('xxxWebsiteBundle:Locations')->createQueryBuilder('l');
            ->where('l.enabled = :enabled')
            ->setParameter('enabled', 1)
        $result= $d
            ->getQuery();

However, if I add a select then it returns an array:

$d = $this->getDoctrine()->getRepository('XXXWebsiteBundle:Locations')->createQueryBuilder('l');
        $d
            ->select('l')
            ->addSelect(
            '( 3959 * acos(cos(radians(' . $latitude . '))' .
                '* cos( radians( l.latitude ) )' .
                '* cos( radians( l.longitude )' .
                '- radians(' . $longitude . ') )' .
                '+ sin( radians(' . $latitude . ') )' .
                '* sin( radians( l.latitude ) ) ) ) as distance'
        )
            ->where('l.enabled = :enabled')
            ->setParameter('enabled', 1)
            ->having('distance < :distance')
            ->setParameter('distance', $requestedDistance)
            ->orderBy('distance', 'ASC');
        $closeresult= $d
            ->getQuery();

So using the first query I could do the following:

foreach($result->getResult() as $location){
    echo $location->getName()
}

However, using the second query I have to use the following which I assume isn't correct:

foreach($result->getResult() as $location){
        echo $location[0]->getName()
    }

Any ideas how I can improve this?

like image 390
user1961082 Avatar asked Mar 07 '13 13:03

user1961082


1 Answers

Since Doctrine ORM 2.2, you can use the HIDDEN keyword.

SELECT a, SOME_EXPR() AS HIDDEN sortCond FROM Entity a ORDER BY sortCond DESC

In your example, it would be like following:

$d = $this
    ->getDoctrine()
    ->getRepository('XXXWebsiteBundle:Locations')
    ->createQueryBuilder('l');

$d
    ->select('l')
    ->addSelect(
        '( 3959 * acos(cos(radians(' . $latitude . '))' .
            '* cos( radians( l.latitude ) )' .
            '* cos( radians( l.longitude )' .
            '- radians(' . $longitude . ') )' .
            '+ sin( radians(' . $latitude . ') )' .
            '* sin( radians( l.latitude ) ) ) ) AS HIDDEN distance'
    )
    ->where('l.enabled = :enabled')
    ->setParameter('enabled', 1)
    ->having('distance < :distance')
    ->setParameter('distance', $requestedDistance)
    ->orderBy('distance', 'ASC');

    $closeresult = $d->getQuery();
like image 87
Ocramius Avatar answered Nov 09 '22 03:11

Ocramius