简体   繁体   中英

Haskell Esqueleto project to list of records instead of tuples

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 

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 

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

given the entity is of course an instance of Show .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM