Haskell“持久”模型:如何正确定义交叉引用?

时间:2018-09-09 18:09:30

标签: database haskell model haskell-persistent

想象一下,您有两个模型( Foo Bar ),它们都相互引用( Foo 具有 barRef 类型为 BarId Bar fooRef 类型为 FooId )。一切顺利:

#!/usr/bin/env stack
{- stack script --resolver=lts-9.21 --package=persistent-template -}
{-# LANGUAGE GADTs, GeneralizedNewtypeDeriving, QuasiQuotes, TemplateHaskell #-}
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses #-}

import Database.Persist.TH

mkPersist sqlSettings [persistLowerCase|
Foo
  barModel BarId
  fooField Int

Bar
  fooModel FooId
  barField Int
|]

main = pure ()

但是,如果我将引用类型包装为也许(仅作为示例,它可能是 Vector 或其他任何东西):

#!/usr/bin/env stack
{- stack script --resolver=lts-9.21 --package=persistent-template -}
{-# LANGUAGE GADTs, GeneralizedNewtypeDeriving, QuasiQuotes, TemplateHaskell #-}
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses #-}

import Database.Persist.TH

mkPersist sqlSettings [persistLowerCase|
Foo
  barModel (Maybe BarId)
  fooField Int

Bar
  fooModel FooId
  barField Int
|]

main = pure ()

由于以下错误而失败:

Not in scope: type constructor or class ‘BarId’

我应该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您在Bar模型中使用的语法不正确。这样的事情应该起作用:

#!/usr/bin/env stack
-- stack script --resolver lts-12.7

{-# LANGUAGE GADTs, GeneralizedNewtypeDeriving, QuasiQuotes, TemplateHaskell #-}
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses #-}

import Database.Persist.TH

mkPersist sqlSettings [persistLowerCase|
Foo
  barModel BarId Maybe
  fooField Int

Bar
  fooModel FooId
  barField Int
|]

main = pure ()

请参阅official docs以供参考。