2017-08-14 102 views
1

我遇到查詢問題。 我想做一個子查詢,但它不返回結果。Laravel子查詢whereIn

這裏是我的代碼:

 $distance_representations = Representation::select('id') 
     ->where(DB::raw('round(6371 * acos(cos(radians(45.0)) * cos(radians(latitude)) * cos(radians(longitude) - radians(2.7)) + sin(radians(45.0)) * sin(radians(latitude)))::numeric, 1) < 50')) 
     ->limit(10) 
     ->get(); 

    $representations = Representation::select('id', 'city', DB::raw('round(6371 * acos(cos(radians(45.0)) * cos(radians(latitude)) * cos(radians(longitude) - radians(2.7)) + sin(radians(45.0)) * sin(radians(latitude)))::numeric, 1) < 50')) 
     ->whereIn('id', $distance_representations) 
     ->get(); 

    return view('search', array('representations' => $representations)); 

的PostgreSQL相當於:

select id, city, round((6371 * acos(cos(radians(45.0)) * cos(radians(latitude)) * cos(radians(longitude) - radians(2.7)) + sin(radians(45.0)) * sin(radians(latitude))))::numeric, 1) as distance 
from representations 
where id in (
    select id 
    from representations 
    where round((6371 * acos(cos(radians(45.0)) * cos(radians(latitude)) * cos(radians(longitude) - radians(2.7)) + sin(radians(45.0)) * sin(radians(latitude))))::numeric, 1) < 50 
    limit 10 
) 

謝謝

+0

你在你的主要select子句中有一個比較 – inarilo

回答

1

也許你可以試試這個

$distance_representations = Representation::find('id') 
    ->where(DB::raw('round(6371 * acos(cos(radians(45.0)) * cos(radians(latitude)) * cos(radians(longitude) - radians(2.7)) + sin(radians(45.0)) * sin(radians(latitude)))::numeric, 1) < 50')) 
    ->limit(10) 
    ->get(); 

    $representations = Representation::all() 
    ->where(DB::raw('round(6371 * acos(cos(radians(45.0)) * cos(radians(latitude)) * cos(radians(longitude) - radians(2.7)) + sin(radians(45.0)) * sin(radians(latitude)))::numeric, 1) < 50')) 
    ->whereIn('id', $distance_representations.id) 
    ->get(); 

希望這會幫助你。

1

我不明白你爲什麼需要子查詢?除非我錯過了某些東西,否則您應該可以使用單個查詢來選擇您的數據。

$representations = Representation::selectRaw('id, city, round(6371 * acos(cos(radians(45.0)) * cos(radians(latitude)) * cos(radians(longitude) - radians(2.7)) + sin(radians(45.0)) * sin(radians(latitude)))::numeric, 1) < 50 AS distance') 
    ->where('distance', '<', 50) 
    ->limit(10) 
    ->get(); 
+0

謝謝你,但是你不能在where子句中使用別名 – jeyGey

1

我找到了解決方案。我無法做得更好。謝謝。

此解決方案正常工作!

$representations_with_distance = Representation::select('id', 'city', DB::raw('round(6371 * acos(cos(radians(?)) * cos(radians(latitude)) * cos(radians(longitude) - radians(?)) + sin(radians(?)) * sin(radians(latitude)))::numeric, 1) as distance')); 

$representation = DB::table(DB::raw("({$representations_with_distance->toSql()}) as rd")) 
    ->where('distance', '<', '?') 
    ->orderBy('distance') 
    ->offset(0) 
    ->limit(10) 
    ->setBindings([$latitude, $longitude, $latitude, $radius]) 
    ->get(); 

return view('search', array('representations' => $representation));