How to get related fields (foreign key) in Yesod?

159 Views Asked by At

I've defined the following models in Yesod application:

CvCategory
    title Text
    order Int
    UniqueCvCategory title

CvItem
    category CvCategoryId
    title Text
    fromYear Int
    toYear Int Maybe
    description Text Maybe
    UniqueCvItem title

I have the following query in a handler:

cvcategories <- selectList [] [] --all cv categories

In my hamlet template, I'd like to do something like:

<ul>
$forall cvcategory <- cvcategories
    <li>$#{cvCategoryTitle cvcategory}
         $forall cvitem <- cvcategory --how?
         <li>#{cvItemTitle cvitem}

In Django, you can easily define a related_name, and then use this to easily access all 'child objects'. Is this possible in Yesod too? How?

1

There are 1 best solutions below

3
arrowd On BEST ANSWER

Change your query, something like

do
  cvcategories <- selectList [] [] --all cv categories
  forM cvcategories $ \cat -> do -- for each category
    cvitems <- selectList [CvCategoryId .== entityKey cat] -- all items belonging to it
    return (cat, cvitems) -- return tuple of category and its items

And then your Hamlet would look like

<ul>
$forall (cvcategory, cvitems) <- cvcategories
    <li>$#{cvCategoryTitle cvcategory}
         $forall cvitem <- items
         <li>#{cvItemTitle cvitem}