Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

haskell - Yesod: Getting a database entity by ID from an Int

I'm new to both Haskell and Yesod, and am trying to build a simple web application that can answer queries from an external API. I have built a parser (using Parsec), that gets me the ID of an entity I want to load as a regular Int value.

However, I for the life of me can't figure out how to turn this Int into something that get will accept (i. e. a Key (?)). All the examples in the documentation only get the id from previous inserts, or from url dispatch.

Any help would be greatly appreciated, since I seem to be stuck... :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Even if the answer can already be found in the comments, I would like to give a complete example.

Assuming we have a Person Model, the following function returns a record for the persion with the given ID (if it exists):

import Database.Persist.Types (PersistValue(PersistInt64))

getByIntId :: Integral i => i -> Handler (Maybe Person)
getByIntId i = runDB $ get $ Key $ PersistInt64 (fromIntegral i)

The import is needed to let us construct the persist-version of an integer. fromIntegral converts any integer to the expected type Int64.

Update: Since Yesod 1.2 PersistValue lives in the module Database.Persist.Types, before 1.2 it was Database.Persist.Store (API Documentation).

Update 2: Since Persistent 2.0.2 there are two build-in functions to convert from/to database keys: toSqlKey and fromSqlKey (API Documentation, see answer by hhefesto for an example).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...