Yesod:通过Int从ID获取数据库实体 [英] Yesod: Getting a database entity by ID from an Int

查看:106
本文介绍了Yesod:通过Int从ID获取数据库实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Haskell和Yesod都很陌生,并且正在尝试构建一个简单的Web应用程序,它可以回答来自外部API的查询。我已经构建了一个解析器(使用Parsec),它可以获取我想要作为常规Int值加载的实体的ID。



然而,我为了我无法弄清楚如何将这个Int变成 get 会接受的东西(即 Key (?) )。文档中的所有示例仅从前面的插入中获得id,或从url派发获得。



任何帮助都将不胜感激,因为我好像被卡住了... :)

解决方案

即使答案已经可以在评论中找到,我想举一个完整的例子。假设我们有一个 Person Model,下面的函数返回给定ID的persion记录(如果存在的话) ):

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

getByIntId :: Integral i =>我 - > Handler(也许是人)
getByIntId i = runDB $ get $ Key $ PersistInt64(fromIntegral i)

需要 import 来让我们构造一个整数的持久版本。 fromIntegral 将任何整数转换为期望的类型 Int64



更新:由于Yesod 1.2 PersistValue 存在于模块 Database.Persist.Types 中,在1.2之前它是 Database.Persist.Store API文档)。

更新2 :从Persistent 2.0.2开始,有两个内置函数可以将数据库键转换为数据库键: toSqlKey fromSqlKey code>( API文档)。

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... :)

解决方案

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).

这篇关于Yesod:通过Int从ID获取数据库实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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