2014-11-02 61 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

相關問題