【问题标题】:Insert list of values into database with persistent使用持久性将值列表插入数据库
【发布时间】:2012-12-25 03:53:52
【问题描述】:

假设我有这段代码(从 "Synopsis" 简化)

{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies, OverloadedStrings #-}
{-# LANGUAGE GADTs, FlexibleContexts #-}
import Database.Persist
import Database.Persist.Sqlite
import Database.Persist.TH
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.Resource (runResourceT)

share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persist|
Person
  name String
|]

main :: IO ()
main = runResourceT $ withSqliteConn ":memory:" $ runSqlConn $ do
  runMigration migrateAll

  johnID <- insert $ Person "John Doe"
  janeID <- insert $ Person "Jane Doe"

  liftIO $ print johnID
  liftIO $ print janeID

  return ()

input = [Person "John Doe", Person "Jane Doe"]

如何插入input 列表并依次接收 ID 列表?

【问题讨论】:

    标签: haskell persistent yesod


    【解决方案1】:

    您可以在runSqlConn 块中使用forM 函数。例如:

    main :: IO ()
    main = runResourceT $ withSqliteConn ":memory:" $ runSqlConn $ do
        runMigration migrateAll
    
        ids <- forM input insert
        liftIO $ print ids
    
      where
        input = [Person "John Doe", Person "Jane Doe"]
    

    【讨论】:

    • 或者更多haskellish,mapM insert input。我知道 RWH 讨论了为什么同时存在 mapMforM
    • 嗯,工作。之前尝试过,它会吐出奇怪的错误消息。谢谢。
    猜你喜欢
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    相关资源
    最近更新 更多