mardi 5 mai 2015

Foreign key constraints in Yesod/Persistent?

I am trying to use Database.Persistant to make a database for a Scotty app, and I cannot figure out the syntax for adding a foreign key constraint between tables. For example, I have a User table and a Post table, and I want the Post table to have an attribute authorId which references UserId in User. This can be accomplished quite easily in raw SQL, but I want to be able to access the data through haskell without resorting to raw sql commands. Also, the constraints would be overwritting upon database migrations. This is what I have at the moment to define the database:

share [mkPersist sqlSettings, mkMigrate "migrateAll"]
[persistLowerCase|
   User
     name String
     email String
     username String
     Primary username
     deriving Show
   Post
     title String
     content T.Text
     author String
     deriving Show
|]

This is fine, but has no key constraints, which can be a very bad thing. If I try to add a foreign key constraint like the wiki on github says, by adding the line Foreign User authorfk author to the Post block, the compiler gives a cryptic error:

 Exception when trying to run compile-time code:
         fieldType mismatch: FTTypeCon Nothing "UserUsername", FTTypeCon Nothing "String"

Which is one of many unhelpful errors that I have encountered trying to make this work. What am I doing wrong? Any assistance or advise would be greatly appreciated.

To be clear, what i want is the author attribute in Post to reference a username in User.

Aucun commentaire:

Enregistrer un commentaire