Haskell Esqueleto项目到记录列表而不是元组 [英] Haskell Esqueleto project to list of records instead of tuples

查看:140
本文介绍了Haskell Esqueleto项目到记录列表而不是元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在所有例子中,我都看到了 esqueleto 被投影到元组列表中。这使得编码和维护更加困难,因为缺乏标签。



例如:

  previousLogItems<  - 从$ \li中选择$  - >>做
orderBy [desc(li ^ .logItemId)]
limit 10
return(li ^。LogItemId,li ^。LogItemTitle)
pre>

有没有办法让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] where Foo is the type of object you query.

You can use the entityVal :: Entity a -> a to obtain the entity that is wrapped into the Entity, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆