How do I define a composite key in Persistent

haskell, persistent, yesod

Solution

You can use the `Primary <field1> <field2>` syntax as per code below.

PrimaryCompositeWithOtherNullableFields
    foo String       maxlen=20
    bar String       maxlen=20
    baz String Maybe
    Primary foo bar   -- THIS LINE --
    deriving Eq Show
    enter code here

The above code is taken from one of the tests at https://github.com/yesodweb/persistent/blob/master/persistent-test/src/CompositeTest.hs#L74

This wiki page explains the different syntax for defining the model in persistent. It really should have been part of the Yesod book.

Problem

How do I declare to Persistent that I have a table the primary key of which is a combination of two fields? For example, assume I have a table containing first_name and last_name, then in SQL syntax I'll need something like: ``` CONSTRAINT pk_PersonID PRIMARY KEY (first_name,last_name) ``` Thanks,

Original source