[英]How to get the associated data using the foreign key
I am trying to write a function that look for the profile of a user or create one if it doesn't exists. 我正在尝试编写一种功能来查找用户的个人资料,或者创建一个不存在的个人资料。
I have used getBy and selectFirst to get the profile of a given user, but I get this error: 我已经使用getBy和selectFirst来获取给定用户的个人资料,但是却出现此错误:
Couldn't match type 'HandlerFor site0' with 'Key' 无法将类型“ HandlerFor site0”与“密钥”匹配
I am using the scaffolding site with postgres. 我正在使用postgres搭建脚手架。
This is my model (user and profile have a one-to-one relationship) 这是我的模型(用户和个人资料具有一对一关系)
User
email Text
password Text Maybe
verkey Text Maybe
verified Bool
UniqueUser email
deriving Typeable
Profile
name Text
userId UserId
UniqueName name
UniqueUserId userId
deriving Typeable
The function is as follow: 功能如下:
getOrCreateProfile :: UserId -> ProfileId
getOrCreateProfile userId = do
mProfile <- runDB $ getBy $ UniqueUserId userId
case mProfile of
Just (Entity pid _) -> return pid
Nothing -> undefined -- insert profile
The error I am getting is: 我得到的错误是:
• Couldn't match type ‘HandlerFor site0’ with ‘Key’
Expected type: Key (Maybe (Entity Profile))
Actual type: HandlerFor site0 (Maybe (Entity Profile))
• In a stmt of a 'do' block:
mProfile <- runDB $ getBy $ UniqueUserId userId
In the expression:
do mProfile <- runDB $ getBy $ UniqueUserId userId
case mProfile of
Just (Entity pid _) -> pid
Nothing -> undefined
In an equation for ‘getOrCreateProfile’:
getOrCreateProfile userId
= do mProfile <- runDB $ getBy $ UniqueUserId userId
case mProfile of
Just (Entity pid _) -> pid
Nothing -> undefined
|
45 | mProfile <- runDB $ getBy $ UniqueUserId userId
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
What am I doing wrong? 我究竟做错了什么? What's the proper way to do this query? 进行此查询的正确方法是什么?
If you look at runDB's type signature : 如果您看一下runDB的类型签名 :
runDB :: YesodDB site a -> HandlerFor site a
you'll see what the problem is. 您将看到问题所在。
Yesod requires you to do some rather elaborate stuff to actually use the query's results - it isn't simply a (Maybe result). Yesod要求您做一些相当复杂的事情才能实际使用查询的结果-这不仅仅是(也许是结果)。 You can find examples here ; 您可以在此处找到示例; this part in particular: 这部分特别是:
people <- runDB $ selectList [] [Asc PersonAge]
defaultLayout
[whamlet|
<ul>
$forall Entity personid person <- people
<li>
<a href=@{PersonR personid}>#{personFirstName person}
|]
Hope this helps. 希望这可以帮助。
This is compiling 这正在编译
getOrCreateProfile :: UserId -> Handler ProfileId
getOrCreateProfile userId = runDB $ do
mProfile <- getBy $ UniqueUserId userId
case mProfile of
Just (Entity pid _) -> return pid
Nothing -> insert $ Profile getTempProfile userId
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.