1

假设我有一张狗名和品种表,如下所示:

share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persist|
Dog
    name Text
    breed Text
    UniqueDog name
|]

我有以下路线:

mkYesod "DogApp" [parseRoutes|
/ RootR GET
/dog/name/#Text DogNameR GET
/dog/id/#DogId DogIdR GET
|]

我正在尝试创建一个页面,根据它的名字返回狗的品种。我可以通过 getDogIdR 路由使用 URL 中的 Id 来做到这一点:

getDogIdR :: DogId -> Handler RepHtml
getDogIdR dogId = do 
    dog <- runDB $ get404 dogId
    defaultLayout $ do
        [whamlet|
<p>
    <b>#{dogName dog}
<p>
    #{dogBreed dog}
|]

但是,如果我尝试使用 getDogNameR 路由创建相同的页面,

getDogNameR :: Text -> Handler RepHtml
getDogNameR maybeDogName = do 
    dog <- runDB $ getBy404 (UniqueDog maybeDogName)
    defaultLayout $ do
        [whamlet|
<p>
    <b>#{dogName dog}
<p>
    #{dogBreed dog}
|]

我收到以下错误:

dog.hs:73:20:
    Couldn't match type `Entity' with `DogGeneric'
    In the return type of a call of `getBy404'
    In the second argument of `($)', namely
      `getBy404 (UniqueDog maybeDogName)'
    In a stmt of a 'do' block:
      dog <- runDB $ getBy404 (UniqueDog maybeDogName)

dog.hs:73:20:
    Kind incompatibility when matching types:
      backend0 :: (* -> *) -> * -> *
      DogGeneric SqlPersist :: *
    In the return type of a call of `getBy404'
    In the second argument of `($)', namely
      `getBy404 (UniqueDog maybeDogName)'
    In a stmt of a 'do' block:
      dog <- runDB $ getBy404 (UniqueDog maybeDogName)

为什么会失败,我该如何解决?

似乎 get404 和 getBy404 函数返回不同的类型。如果我按如下方式更改 getDogNameR 路线,它运行得很好:

getDogNameR :: Text -> Handler RepHtml
getDogNameR maybeDogName = do 
    dog <- runDB $ getBy404 (UniqueDog maybeDogName)
    defaultLayout $ do
        [whamlet|
<p>
    <b>Dog found!
|]
4

1 回答 1

4

似乎 get404 和 getBy404 函数返回不同的类型。

对。

get404 :: (PersistStore (t m), PersistEntity val, Monad (t m), m ~ GHandler sub master,
           MonadTrans t, PersistMonadBackend (t m) ~ PersistEntityBackend val)
           => Key val -> t m val

getBy404 :: (PersistUnique (t m), PersistEntity val, m ~ GHandler sub master,
             Monad (t m), MonadTrans t, PersistEntityBackend val ~ PersistMonadBackend (t m))
             => Unique val -> t m (Entity val)

因此,getBy404将您的狗包裹在Entity您拥有纯狗的地方get404,如果您更换,您的第二个代码应该可以工作

<b>#{dogName dog}

<b>#{dogName (entityVal dog)}

和类似的dogBreed,或者更方便的是,如果你解构返回Entity的绑定

Entity{entityVal = dog} <- runDB $ getBy404 ...
于 2012-12-10T00:25:17.110 回答