Reputation: 573
I have data Book and Author, and Books has a foreign key AuthorId.
I would like to list out books from DB. I need the name of author but book entity just has id of author that why I use get
function to get Author data, but in Hamlet file I could not get the name of Author, because get
function return Maybe Author.
Let see my code:
Book
isbn Text
title Text
description Textarea Maybe
author AuthorId
UniqueBook isbn
Author
name Text
UniqueAuthor name
The get function of request:
getBookListR :: Handler Html
getBookListR = do
books <- runDB $ selectList [BookTitle !=. ""] []
defaultLayout $ do
$(widgetFile "booklistpage")
The booklistpage hamlet file content:
$if not $ null books
<table .table>
$forall Entity bookId book <- books
<tr>
<th th rowspan="4">Image
<td> #{bookTitle book}
<tr>
<td>
$maybe author <- get (bookAuthor book)
#{authorName author}
<tr>
<td> #{bookIsbn book}
<tr>
<td>
$maybe description <- bookDescription book
#{description}
this part of the code has a problem
<td>
$maybe author <- get (bookAuthor book)
#{authorName author}
I got this error:
Handler\BookList.hs:9:19:
Couldn't match expected type `Author'
with actual type `Maybe Author'
In the first argument of `authorName', namely `author_afBtA'
In the first argument of `toHtml', namely `authorName author_afBtA'
In the first argument of `asWidgetT . toWidget', namely
`toHtml (authorName author_afBtA)'
I thought that $maybe will help me, but perhaps I misunderstand the concept. I would like to understand why this code does not work, and what the solution for these kind of cases, when we have only the key when we iterate in hamlet file.
Upvotes: 1
Views: 68
Reputation: 31315
I actually recently added a chapter on SQL joins to the Yesod book, that covers almost exactly this case.
Upvotes: 1