2013-04-25 89 views
8

所以我的/配置/模型看起來像這樣。持久性Yesod中執行多對多的最佳方式是什麼?

Person 
    name Text 
Car 
    name Text 
PersonCar 
    personId PersionId eq 
    carId CarId eq 
    UniquePersonCar personId carId 

假定在數據庫中的輸入分別是Person "Batman"Person "Superman"Car "SUV"Car "Ford"

我目前正在執行此操作以將它們連接到我的處理程序中。

runDB $ do 
    person <- selectFirst [PersonName ==. "Batman"] [] 
    car <- selectFirst [Carname ==. "SUV"] [] 
    let Entity personId _ = case person of 
          Just info -> infor 
          Nothing -> error "no such Person" 
    let Entity carId _ = case car of 
          Just info -> infor 
          Nothing -> error "no such Car" 
    _ <- insert $ PersonCar personId carId 

有沒有更簡單的方法來做到這一點?有做這種表達的慣例嗎?

回答

1

不,目前沒有這種查詢的簡寫(至少我能想到)。

1

調用錯誤會停止您的應用程序。 logError可能會更好。

這是更短:

import Data.Conduit 
import qualified Data.Conduit.List as DCL 

runDB $ do 
    mbPersonId <- runResourceT $ selectKeys [PersonName ==. "Batman"] [] $$ DCL.head 
    mbCarId <- runResourceT $ selectKeys [CarName ==. "SUV"] [] $$ DCL.head 

    case (mbPersonId, mbCarId) of 
     (Just personId, Just carId) -> do 
       _ <- insert $ PersonCar personId carId 
       return() 

     _ -> $(logError) "error looking for Batman and SUV" 
+0

我的處理程序下做它,它給我解析錯誤,任何想法? 'postFromR ::處理程序RepHtml postFormR =做的 FormSuccess RES 情況下結果 - > _ < - runDB $ $插入PersonCar persionId carId _ - > $(LOGERROR) 「錯誤」' – HHC 2013-04-25 14:42:03

+0

@HHC,我已經添加了一個在插入行周圍阻塞,之後需要返回表達式。 使用yesod安裝進行測試,再次獲取代碼。檢查您的型號名稱(PesionId代替PersonId,PesonCar代替PersonCar) – 2013-04-25 16:31:44

相關問題