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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With