1

使用以下持久模式,

Picture
  bytes ByteString
  desc Text Maybe

我想查询SELECT id, desc FROM picture WHERE desc IS NOT NULL。但

previews :: SqlPersistT Handler [(E.Value (Key Picture), E.Value Text)]
previews = E.select $ from $ \pics -> do
  where_ $ pics ?. PictureDesc E.!=. nothing
  return ( pics ^. PictureId
         , pics ?. PictureDesc
         )

• Couldn't match type ‘Maybe (Entity Picture)’
                 with ‘Entity Picture’
  Expected type: SqlExpr (Entity Picture)
    Actual type: SqlExpr (Maybe (Entity Picture))
• In the first argument of ‘(^.)’, namely ‘pics’

我如何实现previews'签名?

4

1 回答 1

0

您尝试使用运算符从非实体中的字段中(?.)获取非Maybe值,但它所做的是从实体中的非字段中获取值。在这里,您的实体实际上不是,因为它不是外部联接的结果。MaybeMaybeMaybeMaybeMaybeMaybe

我认为Value Text如果没有不安全的函数,返回 a 是不可能的,因为过滤where_不会将可空字段的类型更改为不可空。(在我看来,应该有一个投影运算符来做你想做的事情。)

所以你可以这样做

previews :: SqlPersistT Handler [(Value (Key Picture), Value (Maybe Text))]
previews = select $ from $ \pics -> do
  where_ $ not_ . isNothing $ pics ^. PictureDesc
  return ( pics ^. PictureId
         , pics ^. PictureDesc
         )

Maybe使用 Control.Arrow'ssecond和 Data.Maybe's删除fromJust,尽管可能有更优雅的方式:

previews' :: SqlPersistT Handler [(Value (Key Picture), Value Text)]
previews' = do
  xs <- select $ from $ \pics -> do
    where_ $ not_ . isNothing $ pics ^. PictureDesc
    return ( pics ^. PictureId
           , (pics ^. PictureDesc)
           )
  return (map (second $ fmap fromJust) xs)

我没有运行这段代码,只编译了它。

于 2018-02-09T10:15:09.817 回答