从实体记录中获取id

时间:2018-01-24 09:59:09

标签: haskell haskell-persistent

我有Entity record,特别是Entity User,我需要将用户在数据库中的ID称为Int

从阅读docs看起来entityKey在这里很有用,但我不太确定如何获得Int

1 个答案:

答案 0 :(得分:1)

您必须使用fromSqlKeyentityKey的组合。展示它的示例程序:

#!/usr/bin/env stack
{- stack
     --resolver lts-9.0
     --install-ghc
     runghc
     --package persistent
     --package persistent-sqlite
     --package persistent-template
     --package mtl
-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE EmptyDataDecls             #-}
{-# LANGUAGE FlexibleContexts           #-}
{-# LANGUAGE GADTs                      #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE OverloadedStrings          #-}
{-# LANGUAGE QuasiQuotes                #-}
{-# LANGUAGE TemplateHaskell            #-}
{-# LANGUAGE TypeFamilies               #-}
import           Control.Monad.IO.Class  (liftIO, MonadIO)
import Control.Monad.Reader
import           Database.Persist
import           Database.Persist.Sqlite
import           Database.Persist.TH
import Data.Int

share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Person
    name String
    age Int Maybe
    deriving Show
|]

insertPerson :: MonadIO m => ReaderT SqlBackend m (Key Person)
insertPerson =  insert $ Person "Michael" $ Just 26

main :: IO ()
main = runSqlite ":memory:" $ do
    runMigration migrateAll
    michaelId <- insertPerson
    (michael :: Entity Person) <- getJustEntity michaelId
    liftIO $ print $ (fromSqlKey . entityKey $ michael :: Int64)

它的输出:

~/g/scripts $ stack persist.hs
Migrating: CREATE TABLE "person"("id" INTEGER PRIMARY KEY,"name" VARCHAR NOT NULL,"age" INTEGER NULL)
1