2014-06-28 45 views
4

我使用Postgres擴展「earthdistance」來計算經緯度。Sequelize getter方法中的SQL查詢

我也使用Sequelize來訪問數據庫,我想定義一個getter 方法來計算和按一定距離從一組座標進行排序。

下面的查詢工作正常:

SELECT name, 
     earth_distance(ll_to_earth(51.5241182, -0.0758046), 
     ll_to_earth(latitude, longitude)) as distance_from_current_location 
FROM "Branches" 
ORDER BY distance_from_current_location ASC; 

,我還可以使用sequelize.query()使用它,但我希望將所有模型查詢模型的一部分。

如何從模型定義中的getter方法內部指定WHERE條件?

謝謝!

+0

我想用sequelize做同樣的事情在Postgres的。你最終做了什麼? –

回答

0

最好的辦法是將查詢包裝在存儲過程中,並傳入要在where子句中使用的參數。在編譯存儲過程時,這比執行動態生成WHERE子句的動態SQL更好。

添加任何參數和類型,因爲你需要你的存儲過程,結果會是這個樣子:

CREATE FUNCTION GetEarthDistance (v_Foo bigint) RETURNS type AS $$ 
DECLARE 
    v_Name varchar(256); 
BEGIN 
SELECT name INTO v_Name, 
    earth_distance(ll_to_earth(51.5241182, -0.0758046), 
    ll_to_earth(latitude, longitude)) as distance_from_current_location 
FROM Branches 
WHERE somecol > v_foo 
ORDER BY distance_from_current_location ASC; 

RETURN v_Name; 
END; 
$$ LANGUAGE 'plpgsql';