cklm
cklm

Reputation: 926

Get an unmapped field in a native query in Doctrine2

I have a function in Symfony3 with Doctrine2 which is searching for the nearest partner, using latitude and longitude:

public function findNearestPartner($lat,$lng) {

    $rsm=new ResultSetMappingBuilder($this->_em);
    $rsm->addRootEntityFromClassMetadata('AppBundle\Entity\Partner','p');

    $sqlQuery="SELECT p.*, (6371 * acos(cos(radians(:lat)) * cos(radians(p.latitude)) * cos(radians(p.longitude) - radians(:lng)) + sin(radians(:lat)) * sin(radians(p.latitude)))) AS distance
    FROM sp_partner p
    ORDER BY distance ASC
    LIMIT 0,1";

    $query=$this->_em
        ->createNativeQuery($sqlQuery,$rsm)
        ->setParameter('lat',$lat)
        ->setParameter('lng',$lng)
    ;

    return $query->getOneOrNullResult();
}

As you see, I get the nearest Partner-Entity back - but there is also the field "distance", which I don't get back (but it would be very useful). Is there any way to get the value of this field? I read in the docu (http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/native-sql.html), but I can't find anything useful for this case.

Upvotes: 3

Views: 965

Answers (1)

Max P.
Max P.

Reputation: 5679

You can make it through addScalarResult.

$rsm=new ResultSetMappingBuilder($this->_em);
$rsm->addRootEntityFromClassMetadata('AppBundle\Entity\Partner','p');
$rsm->addScalarResult('distance', 'distance');

the result will be

array:2 [▼
  0 => Partner{...},
  distance => xxx
]

Upvotes: 3

Related Questions