Yesod - 错误"无法匹配预期类型"从数据库中提取数据时

时间:2017-01-09 10:56:02

标签: haskell yesod

拥有以下数据库模型,我试图获取事件的城市名称(来自城市的某个字段 - 相关实体):

City json
    name Text
    countryId CountryId
    UniqueCity name
    deriving Eq
    deriving Show
Event
    title Text
    description Text
    date UTCTime
    cityId CityId

extractCityName :: EventId -> Text
extractCityName eventId = do
event <- runDB $ get404 eventId
    city <- runDB $ get404 (eventCityId event)
    x <- cityName city
    return cityName

即使函数尚未调用(在编译时),我也遇到此错误:

Couldn't match expected type `HandlerT site0 IO t0' with actual type `Text'
    In a stmt of a 'do' block: x <- cityName city
    In the expression:
      do { event <- runDB $ get404 eventId;
          city <- runDB $ get404 (eventCityId event);
          x <- cityName city;
          return cityName }

你能帮我弄清楚我的代码有什么问题吗?

1 个答案:

答案 0 :(得分:2)

那是因为runDB的类型签名是YesodDB site a -> HandlerT site IO a。除非您想在yesod handers中运行与数据库相关的操作,否则您将不再需要runDB。提取城市名称的代码如下:

extractCityName :: EventId -> ReaderT SqlBackend IO (Maybe Text)
extractCityName eventId = do
  event <- selectFirst [EventId ==. eventId] [LimitTo 1]
  case event of
    Nothing -> return Nothing
    Just event' -> do
               city <- getJust (eventCityId $ entityVal event')
               return $ Just $ cityName city

现在,您可以在实际需要时使用Yesod处理程序中的上述功能。您可以在结果中进行模式匹配,如果结果为404,则发送Nothing页。