Pregunta

I am using Laravel 4 to redo my site. The hardest part has been converting my queries to Query Builder/Eloquent format. If someone can help me get this one, the longest one, I would be super grateful!

SELECT zipcode, city, state, lat, lng, distance_in_mi
FROM (
SELECT zipcode, city, state, lat, lng, r, ( 3963.17 * ACOS( COS( RADIANS( latpoint ) ) * COS(     RADIANS( lat ) ) * COS( RADIANS( longpoint ) - RADIANS( lng ) ) + SIN( RADIANS( latpoint ) ) * SIN( RADIANS( lat ) ) ) ) AS distance_in_mi
FROM zipcode
JOIN (
SELECT $current_lat AS latpoint, $current_lng AS longpoint, 10 AS r
) AS p
WHERE lat
BETWEEN latpoint - ( r /69 ) 
AND latpoint + ( r /69 ) 
AND lng
BETWEEN longpoint - ( r / ( 69 * COS( RADIANS( latpoint ) ) ) ) 
AND longpoint + ( r / ( 69 * COS( RADIANS( latpoint ) ) ) )
) d
WHERE distance_in_mi <= r
ORDER BY distance_in_mi

Recent Attempt:

$data_object = DB::table('zipcode', function($query)
            {
        $query->select('zipcode, city, state, lat, lng, r, ( 3963.17 * ACOS( COS( RADIANS( latpoint     ) ) * COS( RADIANS( lat ) ) * COS( RADIANS( longpoint ) - RADIANS( lng ) ) + SIN( RADIANS( latpoint ) )     * SIN( RADIANS( lat ) ) ) ) AS distance_in_mi')
          ->from('zipcode')
          ->join('zipcode', function($query1)
            {
            $query1->select("($current_lat AS latpoint, $current_lng AS longpoint, 10 AS r) AS p")
                    ->whereBetween('lat', 'latpoint - ( r /69 )' )
                    ->whereBetween('lng', 'longpoint - ( r / ( 69 * COS( RADIANS( latpoint ) ) ) )     AND longpoint + ( r / ( 69 * COS( RADIANS( latpoint ) ) ) )' );

            })
            })
                    ->where('distance_in_mi', '<=', 'r')
                    ->orderBy('distance_in_mi')
                    ->get();
¿Fue útil?

Solución

You don't need the join and sub select. That's what should work for you:

DB::table('zipcode')
->select(['zipcode','city','state','lat','lang',
    DB::raw("(3963.17*ACOS(COS(RADIANS(latpoint))*COS(RADIANS(lat))*COS(RADIANS(longpoint)-RADIANS(lng))+SIN(RADIANS(latpoint))*SIN(RADIANS(lat)))) 
        AS distance_in_mi, $current_lat AS latpoint, $current_lng AS longpoint, 10 AS r")])
->orderBy('distance_in_mi')
->havingRaw('lat BETWEEN latpoint - (r/69)
    AND latpoint + (r/69)
    AND 
    lng BETWEEN longpoint - (r/(69*COS(RADIANS(latpoint))))
    AND longpoint + (r/(69*COS(RADIANS(latpoint))))
    AND distance_in_mi <= r')
->get();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top