DQL returning an array of entities instead of obje

2019-04-29 17:42发布

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?

1条回答
对你真心纯属浪费
2楼-- · 2019-04-29 18:33

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();
查看更多
登录 后发表回答