我有一个模型

Assignment
   blah Text
   ....

还有一个模型
File
    assignmentId AssignmentId Maybe
    ...

我想在一个连接查询中获取与赋值相关联的所有文件。我尝试过esqueleto和runJoinselectOneMany一起使用,但没有任何运气,因此我正在考虑不使用join或rawsql。这似乎不是个好主意,但我想不通。有人支持这个功能吗?

最佳答案

更新,工作示例:

{-# 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

关于database - 在Maybe Relation上运行加入,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15603927/

10-10 11:25