我使用的是 Datamapper 1.0,后端是 sinatra 和 sqlite3。
我有一些设备,它们有多个位置,我通常只想要设备的最新位置。问题是为上述行生成的 SQL 将查询设备的所有位置,而不仅仅是最新的位置(并且设备可以有 10-20k 个位置)。这显然不是最优的,所以我问:我做错了什么吗?或者 datamapper 以这种方式工作,我必须求助于纯 SQL?有更好的解决方法吗?
我有以下数据模式:
class Location
include DataMapper::Resource
property :id, Serial
property :lat, Integer
property :lon, Integer
property :time, Time
belongs_to :device
end
class Device
include DataMapper::Resource
property :id, Serial
has n, :locations
def lat # and lon
locations.first(:order => [:time.desc]).lat
end
end
请调用 d.first.lat
(其中 d
是使用 Device
获取的 d = Devices.all
)将导致查询所有位置,而不仅仅是第一个匹配的位置。
我只有这两个模型,查询也很简单:
- 在 Controller 中:
@devices = Device.all
- 查看:
@devices.each { |d| d.lat }
- 模型中:
def lat; locations.first.lat; end
谢谢。
最佳答案
我认为诀窍是使用具有 1 个关联
class Device
include DataMapper::Resource
property :id, Serial
has n, :locations # You probably want :order => [:time.desc] here too
has 1, :latest_location, :class_name => Location, :order => [:time.desc]
def lat
latest_location.lat
end
end
关于sql - Datamapper "first"方法正在查询整个关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3327394/