1

我有一个模型

Assignment
   blah Text
   ....

和一个模型

File
    assignmentId AssignmentId Maybe
    ...

我想在连接查询中获取与分配关联的所有文件。我已经尝试过 Esqueleto 和runJoinwithselectOneMany但没有任何运气,所以我正在考虑不使用连接或使用 rawSql。这似乎真的不是一个好主意,但我无法弄清楚这一点。是否支持该功能?

4

1 回答 1

2

更新,工作示例:

{-# 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
于 2013-03-25T11:03:40.600 回答