1

我有一个Entity record,具体来说Entity User,我需要将用户在数据库中的 ID 提取为Int.

从阅读文档来看,这里似乎entityKey很有用,但我不太确定我将如何Int摆脱困境。

4

1 回答 1

1

您必须使用fromSqlKey和的组合entityKey。演示它的示例程序:

#!/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
于 2018-01-24T11:29:16.903 回答