I'm using the Postgres extension 'earthdistance' for lat/long distance calculation.
I'm also using Sequelize to access the database and I want to define a getter method for calculation and sorting by distance from a set of coordinates.
The following query works fine:
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;
And I can use it using sequelize.query(), but I want to keep all the model queries part of the model.
How can I specify WHERE conditions from inside a getter method in the model definition?
Your best bet is probably to wrap the query in a stored procedure and pass in the arguments you want to use in the where clause. As stored procedures are compiled, this will perform better than a Dynamic SQL where you generate the WHERE clause on the fly.
Add whatever parameters and types to your stored proc as you need, and the result will look something like this:
CREATE FUNCTION GetEarthDistance (v_Foo bigint) RETURNS type AS $$
SELECT name INTO v_Name,
earth_distance(ll_to_earth( 51.5241182, -0.0758046 ),
ll_to_earth(latitude, longitude)) as distance_from_current_location
WHERE somecol > v_foo
ORDER BY distance_from_current_location ASC;
$$ LANGUAGE 'plpgsql';