2013-04-25 17 views
8

Quindi il mio/config/modelli assomiglia a questo.Qual è il modo migliore per fare molti-a-molti in Yesod persistente?

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

assumere i ingressi nel database sono Person "Batman"Person "Superman"Car "SUV"Car "Ford" rispettivamente.

Attualmente sto facendo questo per collegarli nel mio gestore.

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 

C'è un modo più semplice per farlo? Esiste una convenzione per fare tale espressione?

risposta

1

No, attualmente non esiste una scorciatoia per questo tipo di query (che posso pensare, almeno).

1

le chiamate all'errore interromperanno l'app. logError potrebbe essere migliore.

Questo è più breve:

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

lo sto facendo sotto un gestore, è dandomi Errore di analisi, tutte le idee? 'postFromR :: Handler RepHtml postFormR = fare risultato caso di FormSuccess res -> _ <- runDB $ inserto $ PersonCar persionId CARID _ -> $ (logError) "errore"' – HHC

+0

@HHC, ho aggiunto un blocco intorno alla riga di inserimento, che ha richiesto un'espressione di ritorno in seguito. Testato con un'installazione yesod, prendi nuovamente il codice. Controlla i nomi dei tuoi modelli (PesionId invece di PersonId, PesonCar invece PersonCar) –

Problemi correlati