2015-05-14 46 views
1

我是Persistent的新手,試圖弄清楚如何使用ID獲取一行。該docs show an example,看起來像這樣:通過ID獲得持久性

personId <- insert $ Person "Michael" "Snoyman" 26 
maybePerson <- get personId 
case maybePerson of 
    Nothing -> liftIO $ putStrLn "Just kidding, not really there" 
    Just person -> liftIO $ print person 

此示例使用從插入產生做查詢ID。我不完全理解它是如何工作的,但這裏的想法是有類型安全鍵,因此無法用BarID查詢Foo。

如何爲我的特定實體生成類型安全的ID /密鑰?我想能夠採取一個Int,例如從一些url路徑,然後查詢我的表作爲一個ID。

+0

你看過Yesod Web框架書的Persistent頁嗎? http://www.yesodweb.com/book/persistent – zigazou

+0

@zigazou正如我在我的問題中鏈接到的,是的。 – LuxuryMode

+0

我也是Persistent和Yesod的新手。這個頁面幫助我理解它是如何工作的。你能更精確地瞭解什麼阻止你?你嘗試過腳手架網站嗎? – zigazou

回答

1

舉個例子,比如說我在models文件有一個Article

Article 
    artname  Text 
    title  Text 
    keywords Text Maybe 
    description Text Maybe 
    body  Markdown 
    parent  ArticleId Maybe 
    user  UserId 
    lastUpdate UTCTime 
    weight  Int 
    public  Bool 

    UniqueArt artname 

    deriving Typeable 

我並不需要創建一個主鍵articleId因爲它是由持續性處理。

在我routes文件:

/new/page      ArticleNewR GET POST 
/page/#ArticleId/edit   ArticleEditR GET POST 
/page/#ArticleId/delete   ArticleDeleteR GET POST 
/page/#ArticleId    ArticleViewR GET 

#ArticleId告訴耶索德只接受ArticleId在我的網址第二個參數。 Article*R只是每個URL的處理程序。

Handler/Article.hs,我需要有相應的函數處理程序。例如,如果我告訴ArticleViewR GET處理的耶索德,我需要定義以下功能:

getArticleViewR :: ArticleId -> Handler Html 
getArticleViewR articleId = do 
    -- The article 
    article <- runDB $ get404 articleId 

    -- The parent article (if any) 
    let parentIdM = articleParent article 
    parentM <- case parentIdM of 
        Just parentId -> runDB $ get parentId 
        Nothing -> return Nothing 

    -- The child articles 
    children <- runDB $ selectList [ArticleParent ==. Just articleId] 
            [Asc ArticleWeight, Asc ArticleTitle] 

    -- Author 
    author <- runDB $ get (articleUser article) 

    defaultLayout $ do 
     setTitle $ toHtml (articleTitle article) 
     setDescription $ articleDescription article 
     setKeywords $ articleKeywords article 
     setAuthor $ userUsername <$> author 
     $(widgetFile "article/view") 

這基本上是你如何鏈接每件。

+0

這非常有幫助,謝謝!但是我沒有使用Yesod。我將Persistent作爲一個獨立的ORM與Scotty一起用於Web上的事物。 – LuxuryMode