Laravel DB :: Raw无法按预期工作

时间:2017-08-01 13:52:17

标签: php laravel eloquent

我正在形成以下查询:

SELECT *, ACOS( SIN( RADIANS( `latitude` ) ) * SIN( RADIANS('17.4073331') ) + COS( RADIANS( `latitude` ) )* COS( RADIANS('17.4073331')) * COS( RADIANS( `longitude` ) - RADIANS('78.3802307'))) * 6380 AS distance 
FROM bbq_branches_by_city 
HAVING distance <= 20

我在laravel中的表现如下:

DB::table('bbq_branches_by_city')
  ->select(DB::raw("*, ACOS( SIN( RADIANS( `latitude` ) ) * SIN( RADIANS($lat) ) + COS( RADIANS( `latitude` ) )* COS( RADIANS($lat)) * COS( RADIANS( `longitude` ) - RADIANS($long))) * 6380 AS distance"))
  ->havingRaw("distance <= 20")
  ->get();

你能让我知道我错在哪里吗?

2 个答案:

答案 0 :(得分:2)

试试这个:

DB::table('bbq_branches_by_city')
     -> select(["*",DB::raw("ACOS( SIN( RADIANS( `latitude` ) ) * SIN( RADIANS($lat) ) + COS( RADIANS( `latitude` ) )* COS( RADIANS($lat)) * COS( RADIANS( `longitude` ) - RADIANS($long))) * 6380 AS distance")])
     ->havingRaw("distance<=20")
     ->get();

只需将选择设为数组,例如['*','distance']

答案 1 :(得分:0)

您可以根据running-queries

尝试以下代码
$data = DB::select('select *,ACOS( SIN( RADIANS( `latitude` ) ) * SIN( RADIANS('17.4073331') ) + COS( RADIANS( `latitude` ) )* COS( RADIANS('17.4073331')) * COS( RADIANS( `longitude` ) - RADIANS('78.3802307'))) * 6380 AS distance from bbq_branches_by_city having distance<=20');