SQL search using Haversine in Doctrine

2019-06-07 22:46发布

问题:

I want to do a search by coordinates, i.e. I want to have a function that works like this:

function getLocationsInCircle($lat, $long, $minDist, $maxDist){
    //return all the places that are at least $minDist 
    //kilometers away and no more than $maxDist kilometers away
}

I have a "location" table that stores all location Ids and their latitude and longitude.

The haversine formula is good enough for what I want to do

6371 * ACOS(SIN(RADIANS( $lat )) * SIN(RADIANS( latitude )) + COS(RADIANS( $lat )) * COS(RADIANS( latitude )) * COS(RADIANS( longitude ) - RADIANS( $long )))

I just don't see how to run that query in Doctrine.

回答1:

Try this :

Doctrine_query::create()->select('id')
    ->addSelect("(6371 * ACOS(SIN(RADIANS($latitude)) * SIN(RADIANS(l.latitude)) + COS(RADIANS($latitude)) * COS(RADIANS(l.latitude)) * COS(RADIANS(l.longitude) - RADIANS($longitude)))) as Distance")
    ->from('Location l')
    ->having("Distance > $minDist AND Distance < $maxDist");