如何在Laravel,子查询中加入

时间:2014-04-17 01:56:01

标签: php mysql laravel-4 eloquent

我正在使用Laravel 4重做我的网站。最困难的部分是将查询转换为Query Builder / Eloquent格式。如果有人能帮助我得到这个最长的那个,我会非常感激!

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

最近的尝试:

$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();

1 个答案:

答案 0 :(得分:1)

您不需要加入和子选择。这应该适合你:

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();