2016-04-18 33 views
2

我創建了一個函數,用於加載一些Entities,但我有一些麻煩明白我應該怎麼把它的類型聲明,所以我把這個Yesod book chapter 約耶索德單子,以便更好地瞭解它,我來到這個片段:YesodDB,如何把各類正確

-- type Distance = Int 
worksByNhood :: AdrNhoodId -> Int64 -> Int64 -> YesodDB App [(Entity Work, Int, [Entity WImage])] 
worksByNhood nId offset' limit' = do 
    works <- select $ from $ \(w `InnerJoin` d) -> do 
    on $ d ^. AdrDistanceNhood2 ==. w ^. WorkNhood 
    where_ (d ^. AdrDistanceNhood1 ==. val nId) 
    orderBy [asc (d ^. AdrDistanceDistance)] 
    offset offset' 
    limit limit' 
    return (w, d ^. AdrDistanceDistance) 
    works' <- forM works $ \([email protected](Entity wId _), d) -> do 
    images <- select $ from $ \wi -> do 
     where_ (wi ^. WImageWork ==. val wId) 
     return wi 
    return (w, d, images); 
    return works' 

我覺得這Int在聲明中需要被轉換好歹,更具體的類型,我收到此錯誤:

Select.hs:20:12: 
    Couldn't match type ‘Database.Esqueleto.Value Distance’ with ‘Int’ 
    Expected type: (Entity Work, Distance, [Entity WImage]) 
     Actual type: (Entity Work, 
        Database.Esqueleto.Value Distance, 
        [Entity WImage]) 
    In the first argument of ‘return’, namely ‘(w, d, images)’ 
    In a stmt of a 'do' block: return (w, d, images) 
    In the expression: 
     do { images <- select $ from $ \ wi -> do { ... }; 
      return (w, d, images) } 

回答

2

我記得有一個chapter about joins in the great Yesod book,所以我又看了一遍,並找到了解決辦法,也許我的代碼可以幫助別人,所以這裏有雲:

module Select where 

import Import hiding((==.), on, Value) 
import Database.Persist.Sql (toSqlKey) -- Useful when I want to explicitly use primary keys 
import Database.Esqueleto 

-- type Distance = Int 
worksByNhood :: AdrNhoodId -> Int64 -> Int64 -> YesodDB App [(Entity Work, Value Distance, [Entity WImage])] 
worksByNhood nId offset' limit' = do 
    works <- select $ from $ \(w `InnerJoin` d) -> do 
    on $ d ^. AdrDistanceNhood2 ==. w ^. WorkNhood 
    where_ (d ^. AdrDistanceNhood1 ==. val nId) 
    orderBy [asc (d ^. AdrDistanceDistance)] 
    offset offset' 
    limit limit' 
    return (w, d ^. AdrDistanceDistance) 
    forM works $ \([email protected](Entity wId _), d) -> do 
    images <- select $ from $ \wi -> do 
     where_ (wi ^. WImageWork ==. val wId) 
     return wi 
    return (w, d, images) 

Value Distance的類型聲明是答案