将此复杂查询转换为ORM或Laravel查询生成器

时间:2014-04-15 20:23:55

标签: php mysql orm laravel-4

我一直在尝试将此查询转换为laravel兼容查询。我无法在查询中找到有关使用AS的任何信息。任何帮助将不胜感激。

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)

基于this question

回答:

Laravel支持使用AS的表和列的别名。尝试

$users = DB::table('really_long_table_name AS t')
           ->select('t.id AS uid')
           ->get();

基于此,您可以创建查询,只需将AS放入选择或表格中。