运行加入上也许关系(Running join on Maybe Relation)

2019-10-17 21:13发布

我有一个模型

Assignment
   blah Text
   ....

和模型

File
    assignmentId AssignmentId Maybe
    ...

我想在一个连接查询分配相关联的所有文件。 我曾尝试Esqueleto和runJoinselectOneMany ,但还没有任何运气,所以我正在考虑不使用加入,或使用rawSql。 这确实似乎不是一个好主意,但我不知道这一点。 是否有该功能的任何支持?

Answer 1:

更新,工作示例:

{-# LANGUAGE PackageImports, OverloadedStrings, ConstraintKinds #-}
module Handler.HTest where

import Import
import "esqueleto" Database.Esqueleto as Esql
import "monad-logger" Control.Monad.Logger (MonadLogger)
import "resourcet" Control.Monad.Trans.Resource (MonadResourceBase)
import qualified Data.List as L

getFilesByAssignment :: (PersistQuery (SqlPersist m), MonadLogger m
                                                  , MonadResourceBase m) =>
                        Text -> SqlPersist m [Entity File]
getFilesByAssignment myAssign = do
  result <- select $
        from $ \(assign `InnerJoin` file) -> do
          on (just (assign ^. AssignmentId)
            Esql.==. file ^. FileAssignmentId)
          where_ (assign ^. AssignmentBlah Esql.==. val myAssign)
          return (assign, file)

  return $ map snd (result :: [(Entity Assignment, Entity File)])

(.$) = flip ($)

getTestR :: Handler RepHtml
getTestR = do
       entFiles <- runDB $ getFilesByAssignment "test"
       defaultLayout $ do
               setTitle "Test page"
               entFiles .$ map (show . unKey . entityKey)
                        .$ L.intercalate ", "
                        .$ toHtml
                        .$ toWidget


文章来源: Running join on Maybe Relation