Reputation: 7035
I'd like to display a list of items in a webpage, along with associated details from a separate table (with a many-to-one relationship). How do I do this in Yesod? I am using the default scaffolding. The upshot is that runDB
cannot be nested in a WidgetT
context — or so I think.
To make this more concrete, how do I define the function featuresAssociatedWith
to use in the following hamlet code:
<h2> Cars
$forall Entity carId car <- carList
<div class="car-item">
<h3> #{carYear car} #{carMake car} #{carModel car}
<ul>
$forall feature <- featuresAssociatedWith carId
<li> #{feature}
Given the following models:
Car
make Text
model Text
year Int
CarFeature
car CarId
text Text
UniqueCF car text
Here is the current handler function
getCarListR :: Handler Html
getCarListR = do
carList <- runDB $ selectList [] [Asc CarOrder]
liftIO $ print $ length carList
defaultLayout $ do
setTitle "Cars"
$(widgetFile "carList")
It seems most natural to embed a runDB
query in the Widget this way, but again, this isn't possible:
featuresAssocWith :: CarId -> [Entity CarFeature]
featuresAssocWith carID = selectList [CarFeatureCar ==. carID] []
Upvotes: 2
Views: 68
Reputation: 31315
Hamlet is designed to not allow you to perform actions like database queries inside of it. Instead, you'll need to perform the query outside of hamlet, and then pass in a list of tuples of car info together with the data from the associated table.
Upvotes: 2