我有一个基于DataMapper的SQLite数据库。我将构建模型所依据的数据的时间存储为模型Msrun
的Msrun.rawtime
或property :rawtime, DateTime
。
我需要做的是在筛选器中选择日期/时间范围,然后根据该时间筛选器对DataMapper条目进行排序。如下所示:
Msrun.all.size # => 63
matches = Msrun.all( begintime: 2010-11-03T21:33:00-0600, endtime: 2011-04-09T23:59:59-0600 )
matches.size # => 12
由于我的数据库在这个模型和子模型之间有大约500个属性,并且我希望每个月生成大约100个这样的条目,所以我也想要一些非常快的东西。这需要SQL吗?这个是可能的吗?我是不是让这件事变得更难了/有没有一种更简单的方法来配置我的数据来启用这种排序?
发布于 2011-06-16 04:37:24
我不知道你想做什么?如果要查询在特定起始时间和终止时间之间发生的项目,您可以使用:
Mrsun.all(:rawtime => start_time..end_time)
这将生成如下所示的SQL
SELECT ... FROM msruns WHERE rawtime > start_time AND rawtime < end_time;
这回答了你的问题吗?
更完整的示例:
require 'rubygems'
require 'dm-core'
require 'dm-migrations'
# setup the logger
DataMapper::Logger.new($stdout, :debug)
# connect to the DB
DataMapper.setup(:default, 'sqlite3::memory:')
class Msrun
include DataMapper::Resource
# properties
property :id, Serial
property :rawtime, DateTime
end
DataMapper.finalize.auto_migrate!
10.times do |n|
Msrun.create(:rawtime => DateTime.new(2011, 1, 1, 0, 0 , n))
end
p Msrun.all(:rawtime => DateTime.parse('2011-1-1T00:00:04+0100')..DateTime.parse('2011-1-1T00:00:07+0100'))
https://stackoverflow.com/questions/6363630
复制相似问题