Haskell Esqueleto项目到记录列表而不是元组 [英] Haskell Esqueleto project to list of records instead of tuples
问题描述
在所有例子中,我都看到了 esqueleto 被投影到元组列表中。这使得编码和维护更加困难,因为缺乏标签。
例如:
previousLogItems< - 从$ \li中选择$ - >>做
pre>
orderBy [desc(li ^ .logItemId)]
limit 10
return(li ^。LogItemId,li ^。LogItemTitle)
有没有办法让esqueleto将结果投影到记录列表中?
解决方案实际上,你自己构造元组。事实上:
previousLogItems< - 从$ \li选择$ - - > do
orderBy [desc(li ^。LogItemId)]
limit 10
return (li ^。LogItemId,li ^。LogItemTitle)因此,您可以使用
(^。)::(PersistEntity val,PersistField typ)=> expr(实体val) - > EntityField val typ - > expr(Value typ)
selector获取字段并将它们包装到一个元组中。
你可以这样写:
previousLogItems> - 从$ \li选择$ - >>做
orderBy [desc(li ^。LogItemId)]
limit 10
return li您将获得
[Entity Foo]
的列表,其中Foo
是类型您可以使用 -Persist.html#t:Entityrel =nofollow noreferrer>entityVal :: Entity a - >
来获取包装到Entity
中的实体,例如:previousLogItems< - 从$ \li选择$ - - > do
orderBy [desc(li ^。LogItemId)]
limit 10
return li
mapM_(print。entityVal)previousLogItems给定实体当然是
Show
的实例。In all the examples I have seen the results from esqueleto are projected into a list of tuples. This makes coding and maintenance harder because of lack of labels.
For example:
previousLogItems <- select $ from $ \li -> do orderBy [desc (li ^. LogItemId)] limit 10 return (li ^. LogItemId, li ^. LogItemTitle)
Is there any way to get esqueleto to project the results to a list of records instead?
解决方案In fact you construct the tuple yourself. Indeed:
previousLogItems <- select $ from $ \li -> do orderBy [desc (li ^. LogItemId)] limit 10 return (li ^. LogItemId, li ^. LogItemTitle)
You thus make use of the
(^.) :: (PersistEntity val, PersistField typ) => expr (Entity val) -> EntityField val typ -> expr (Value typ)
"selector" to obtain the fields and wrap them into a tuple.If you write it like:
previousLogItems >- select $ from $ \li -> do orderBy [desc (li ^. LogItemId)] limit 10 return li
You will obtain a list of
[Entity Foo]
whereFoo
is the type of object you query.You can use the
entityVal :: Entity a -> a
to obtain the entity that is wrapped into theEntity
, for example:previousLogItems <- select $ from $ \li -> do orderBy [desc (li ^. LogItemId)] limit 10 return li mapM_ (print . entityVal) previousLogItems
given the entity is of course an instance of
Show
.这篇关于Haskell Esqueleto项目到记录列表而不是元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!