在Handler中提取数据库字段值 [英] Extracting database field values inside a Handler
问题描述
我想提取数据库字段(Text)并将其作为参数传递给Handler的另一个函数。但是,我碰到类型错误。完全组成的例子可能会让人觉得有点做作,但应该说明我遇到的问题。
Person
name Text
Car
personId PersonId
名称文本
类型文本
我想要一个Car实体,然后找到相应的人。获取他的名字,然后将其作为参数传递。例如:
data MyD = MyD {input1 :: Int}
entryForm :: Text - > Form MyD - Update:删除不正确的额外参数
entryForm n1 = renderDivs $ MyD
< $> areq intField n1 Nothing
我的get处理程序看起来像:
getInputR :: CarId - > Handler Html
getInputR carId = do
car< - runDB $ get404 carId
pid< - carPersonId car
名称< - getPName pid
(窗口小部件,enctype )< - generateFormPost $ entryForm name
defaultLayout $ do
$(widgetFilemy_template)
其中
getPName pid = do
person< - runDB $ get404 pid
personName person
我收到一个错误消息:
无法与实际类型`KeyBackend
persistent-1.2.1:预期类型'HandlerT App IO t0'
匹配:Database.Persist .Sql.Types.SqlBackend Person'
在'carPersonId'的调用的返回类型中
在'do'块的句柄中:pid< - carPersonId car
$
谢谢!
解决方案尝试更改
pid < - carPersonId车
名称< - getPNa me pid
至
name< - getPName $ carPersonId car
从 runDB
调用不在处理程序monad中,所以您不需要使用箭头语法来访问它。
第二个错误,问题类似: getPName
函数的返回类型在Handler monad中,因为它使用 runDB
,因此您需要使用 return
将值放入monad中:
getPName pid = do
person< - runDB $ get404 pid
return $ personName person
I would like to extract a database field (Text) and pass it as an argument to another function from a Handler. However, I run into Type errors. Completely made up example so may feel a bit contrived but should illustrate the issue I am having.
Person
name Text
Car
personId PersonId
name Text
type Text
I would like to get a Car entity and then find the corresponding Person. Get his name and then pass it as an argument. Something like:
data MyD = MyD { input1 :: Int}
entryForm :: Text -> Form MyD -- Update: Removed the incorrect extra parameter
entryForm n1 = renderDivs $ MyD
<$> areq intField n1 Nothing
My get handler looks like:
getInputR :: CarId -> Handler Html
getInputR carId = do
car <- runDB $ get404 carId
pid <- carPersonId car
name <- getPName pid
(widget, enctype) <- generateFormPost $ entryForm name
defaultLayout $ do
$(widgetFile "my_template")
where
getPName pid = do
person <- runDB $ get404 pid
personName person
I get an error saying:
Couldn't match expected type `HandlerT App IO t0'
with actual type `KeyBackend
persistent-1.2.1:Database.Persist.Sql.Types.SqlBackend Person'
In the return type of a call of `carPersonId'
In a stmt of a 'do' block: pid <- carPersonId car
What am I doing wrong?
Thanks!
解决方案 Try changing
pid <- carPersonId car
name <- getPName pid
to
name <- getPName $ carPersonId car
The value returned from your runDB
call is not inside the handler monad so you don't need to use the arrow syntax to access it.
For the second error, the issue is similar: The getPName
function's return type is in the Handler monad since it uses runDB
, so you need to use return
to put the value into the monad:
getPName pid = do
person <- runDB $ get404 pid
return $ personName person
这篇关于在Handler中提取数据库字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!