加入Maybe Fields

时间:2014-05-12 01:07:50

标签: haskell yesod esqueleto

我有一张带有外键的桌子。我想加入但不能让它编译。

CatTable
   name Text

MyTable
   category CatTableId Maybe
   amount Double    

我的查询:

myQuery :: (PersistQuery (SqlPersistT m), MonadLogger m , MonadResourceBase m) =>
                        SqlPersistT m [(E.Value (Maybe (Text)), E.Value (Maybe Double))]
myQuery = do
  E.select $ E.from $  \(t `E.LeftOuterJoin` c) -> do
        E.on (t E.?. MyTableCategory E.==. E.just (c E.^. CatTableId))
        E.groupBy $ E.just (c E.^. CatTableName)
        let sum' = E.sum_ (t E.^. MyTableAmount)
        E.orderBy [E.desc sum']
        return (E.just (c E.^. CatTableName) , sum' )

我收到此类错误:

Couldn't match type `KeyBackend SqlBackend CatTable'
              with `Maybe (KeyBackend SqlBackend CatTable)'
Expected type: EntityField
                 CatTable (Maybe (KeyBackend SqlBackend CatTable))
  Actual type: EntityField
                 CatTable (KeyBackend SqlBackend CatTable)
In the second argument of `(^.)', namely `CatTableId'
In the first argument of `just', namely `(c ^. CatTableId)'
In the second argument of `(E.==.)', namely
  `just (c ^. CatTableId)'

Couldn't match type `Maybe (Entity MyTable)' with `Entity MyTable'
Expected type: SqlExpr (Entity MyTable)
  Actual type: SqlExpr (Maybe (Entity MyTable))
In the first argument of `(^.)', namely `t'
In the first argument of `sum_', namely `(t ^. MyTableAmount)'
In the expression: sum_ (t ^. MyTableAmount)

我尝试了^.?.的不同组合,但没有运气。还尝试删除或添加just。在这一点上,我只是在猜测而不了解如何解决错误。所以欣赏有关如何加入Maybe字段的任何输入。我假设groupBy可能使它复杂化,因为它不是CatTable中的Maybe,但它会在它加入之后。

 select * from cat_table;
 id|name
 1|A
 2|B
 3|C

 select * from my_table;
 id|category|amount
 1|1|55.0
 2|1|15.0
 3|2|10.0
 4|2|60.0
 5||60.0


select name, sum(amount) from my_table as m left join cat_table as c
       on m.category = c.id 
       group by name;


|60.0
A|70.0
B|70.0

1 个答案:

答案 0 :(得分:1)

此查询有效。我在我的问题和这个问题中发布的查询之间的差异实际上是?.我认为我尝试了这种变化但可能错过了显而易见的问题。 我还不清楚我们何时会使用?.。我注意到,如果删除E.just并使用?. CatTable Entity (c),我也会收到有效的查询。

myQuery :: (PersistQuery (SqlPersistT m), MonadLogger m , MonadResourceBase m) =>
                        SqlPersistT m [(E.Value (Maybe Text), E.Value (Maybe Double))]
myQuery = do
  E.select $ E.from $  \(t `E.LeftOuterJoin` c) -> do
        E.on (t E.^. MyTableCategory E.==. E.just (c E.^. CatTableId))
        E.groupBy $ E.just (c E.^. CatTableName)
        let sum' = E.sum_ (t E.^. MyTableAmount)
        E.orderBy [E.desc sum']
        return (E.just (c E.^. CatTableName) ,sum')