Yesod:通过 ID 从 Int 获取数据库实体
我对 Haskell 和 Yesod 都很陌生,我正在尝试构建一个简单的 Web 应用程序来回答来自外部 API 的查询。我已经构建了一个解析器(使用 Parsec),它可以获取我想要作为常规 Int 值加载的实体的 ID。
然而,我一生都无法弄清楚如何将这个 Int 转换为 get
会接受的东西(即 Key
(?))。文档中的所有示例仅从之前的插入或 url 调度中获取 id。
任何帮助将不胜感激,因为我似乎陷入困境......:)
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... :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
即使答案已经可以在评论中找到,我还是想给出一个完整的例子。
假设我们有一个
Person
模型,以下函数返回具有给定 ID 的人的记录(如果存在):需要
import
来让我们构造持久化- 整数的版本。fromIntegral
将任何整数转换为预期类型Int64
。更新:从 Yesod 1.2
PersistValue
开始,位于Database.Persist.Types
模块中,在 1.2 之前,它是Database.Persist.Store< /code> (API 文档)。
更新 2:自 Persistent 2.0.2 起,有两个内置函数可用于将数据库密钥转换为数据库密钥:
toSqlKey
和fromSqlKey
(API 文档,请参阅 hhefesto 的回答示例) 。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):The
import
is needed to let us construct the persist-version of an integer.fromIntegral
converts any integer to the expected typeInt64
.Update: Since Yesod 1.2
PersistValue
lives in the moduleDatabase.Persist.Types
, before 1.2 it wasDatabase.Persist.Store
(API Documentation).Update 2: Since Persistent 2.0.2 there are two build-in functions to convert from/to database keys:
toSqlKey
andfromSqlKey
(API Documentation, see answer by hhefesto for an example).PersistInt64
位于:Database.Persist.Types
。以前,
PersistInt64
位于:Database.Persist.Store
。PersistInt64
is here:Database.Persist.Types
.Previously
PersistInt64
was here:Database.Persist.Store
.只是一个如何使用 toSqlKey 的示例(持久 2.0.2)
Just an example of how to use toSqlKey (Persistent 2.0.2)