我有一个实体定义,其中包含UTCTime
类型的字段。
Foo
time UTCTime
...
我想选择一系列按时间排序的实体。如果两个实体有相同的时间,我不在乎哪一个是第一个,我只想让订单每次都相同。实体键是唯一的,它似乎按键排序将是完美的 选择。
是否可以执行selectList之类的查询并按主键排序匹配的行? 可替代地
当然,我总是可以按时间要求订购,然后自己按键订购退回的列表。但这排除了使用SelectOp s OffsetBy
和LimitTo
,因为我事先无法知道有多少实体会有相同的时间。
答案 0 :(得分:3)
我不确定SelectOpt
仅适用于实体值,所以我在一小段代码中检查了它。假设一个实体看起来像这样:
EntityA
key Text
time UTCTime
deriving Show
您可以列出您感兴趣的SelectOpt
并获得理想的输出。
示例代码如下所示:
main :: IO ()
main = runSqlite ":memory:" $ do
runMigration migrateAll
currentTime <- liftIO getCurrentTime
-- insert some data
_ <- insert $ EntityA "first" currentTime
_ <- insert $ EntityA "second" currentTime
_ <- insert $ EntityA "third" currentTime
_ <- insert $ EntityA "fourth" currentTime
currentTime <- liftIO getCurrentTime
-- insert more data
_ <- insert $ EntityA "fifth" currentTime
_ <- insert $ EntityA "sixth" currentTime
_ <- insert $ EntityA "seventh" currentTime
_ <- insert $ EntityA "eighth" currentTime
currentTime <- liftIO getCurrentTime
-- insert more data
_ <- insert $ EntityA "this one will be first" currentTime
sorted <- selectList [] [Desc EntityATime, Asc EntityAId]
mapM_ (liftIO . print) sorted
,输出为:
Migrating: CREATE TABLE "entity_a"("id" INTEGER PRIMARY KEY,"key" VARCHAR NOT NULL,"time" TIMESTAMP NOT NULL)
Entity {entityKey = Key {unKey = PersistInt64 9}, entityVal = EntityA {entityAKey = "this one will be first", entityATime = 2014-05-07 20:15:35.627561 UTC}}
Entity {entityKey = Key {unKey = PersistInt64 5}, entityVal = EntityA {entityAKey = "fifth", entityATime = 2014-05-07 20:15:35.627026 UTC}}
Entity {entityKey = Key {unKey = PersistInt64 6}, entityVal = EntityA {entityAKey = "sixth", entityATime = 2014-05-07 20:15:35.627026 UTC}}
Entity {entityKey = Key {unKey = PersistInt64 7}, entityVal = EntityA {entityAKey = "seventh", entityATime = 2014-05-07 20:15:35.627026 UTC}}
Entity {entityKey = Key {unKey = PersistInt64 8}, entityVal = EntityA {entityAKey = "eighth", entityATime = 2014-05-07 20:15:35.627026 UTC}}
Entity {entityKey = Key {unKey = PersistInt64 1}, entityVal = EntityA {entityAKey = "first", entityATime = 2014-05-07 20:15:35.626622 UTC}}
Entity {entityKey = Key {unKey = PersistInt64 2}, entityVal = EntityA {entityAKey = "second", entityATime = 2014-05-07 20:15:35.626622 UTC}}
Entity {entityKey = Key {unKey = PersistInt64 3}, entityVal = EntityA {entityAKey = "third", entityATime = 2014-05-07 20:15:35.626622 UTC}}
Entity {entityKey = Key {unKey = PersistInt64 4}, entityVal = EntityA {entityAKey = "fourth", entityATime = 2014-05-07 20:15:35.626622 UTC}}
如果您感兴趣,我可以发布示例项目(它在fpcomplete.com上),但我想这很好地说明了它。