我正在使用postgis根据远离用户的距离对数据进行排序。由于postgis在给出信息之前计算距离,有什么方法可以在给我回信息时将值设置为距离属性?我不希望它存储在数据库中,只是希望在检索时设置它。这就是我用来在我的模型中进行排序的方法。提前谢谢。
scope :distance, ->(userLat, userLng) {
order(
%{
ST_Distance_Sphere(
ST_GeomFromEWKT(
'SRID=4326;POINT(' || properties.lng || ' ' || properties.lat || ')'
),
ST_GeomFromEWKT('SRID=4326;POINT(%f %f)')
)
} % [userLng, userLat])
}
答案 0 :(得分:0)
不,如果该值是由Postgres计算的,那么Postgres显然必须在排序期间计算它。如果你没有使用距离计算作为一个字段来对数据库进行非规范化,那么你可以创建一个数据库视图并将模型置于其上。
create view properties_distance as
select ST_Distance_Sphere(
ST_GeomFromEWKT(
'SRID=4326;POINT(' || properties.lng || ' ' || properties.lat || ')'
),
ST_GeomFromEWKT('SRID=4326;POINT(%f %f)')
) as distance, lng, lat from properties;