2014-11-02 55 views
1

我有数据Book和Author,Books有一个外键AuthorId。 我想列出来自DB的书籍。我需要作者的名字,但是图书实体只有我的作者id,为什么我使用get函数获取Author数据,但是在Hamlet文件中,我无法得到Author的名字,因为get函数返回Maybe Author。如何通过哈姆雷特的外键获取其他表的值?

让看到我的代码:

Book 
    isbn Text 
    title Text 
    description Textarea Maybe 
    author AuthorId 
    UniqueBook isbn 
Author 
    name Text 
    UniqueAuthor name 

请求get函数:

getBookListR :: Handler Html 
getBookListR = do 
     books <- runDB $ selectList [BookTitle !=. ""] [] 
     defaultLayout $ do 
       $(widgetFile "booklistpage") 

的booklistpage村庄文件内容:

$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} 

的这部分代码有问题

  <td> 
      $maybe author <- get (bookAuthor book) 
        #{authorName author} 

我得到这个错误:

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)' 

我想,也许$会帮我,但也许我误解的概念。我想知道为什么这个代码不起作用,以及当我们在哈姆雷特文件中迭代时只有关键字时,这些类型的解决方案是什么。

回答

1

我真的最近added a chapter on SQL joins到Yesod书,几乎涵盖这种情况。

+1

谢谢Micheal!我有你的书是2012年的O'Reilly one。 – bitli 2014-11-02 16:34:56

+0

谢谢。我们正在编写第二版以推出最新的更改,因此请在未来几个月内继续关注此更新。 – 2014-11-02 17:22:38

相关问题