I have a table with a Maybe Foreign Key. I am trying to join but cannot get it to compile.
CatTable
name Text
MyTable
category CatTableId Maybe
amount Double
My query:
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' )
and I get this type error:
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)
I have tried different combinations of ^.
and ?.
but no luck. Also tried removing or adding just
too. At this point this I am just guessing without understanding how to resolve the error. So appreciate any input on how to join on a field of Maybe. I am presuming the groupBy
is probably complicating it as it is not a Maybe in the CatTable but it will be once it gets joined.
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
This query works. The difference between the query I had posted in my question and this one is really the ?.
I thought I tried that variation but perhaps missed the obvious. I am still unclear when we will use . I noticed I also get a working query if removed ?.
though. E.just
and used ?.
for the 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')