Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define a composite key in Persistent

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,

like image 951
Uri Barenholz Avatar asked May 03 '12 14:05

Uri Barenholz


1 Answers

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.

like image 146
Mikkel Avatar answered Sep 28 '22 04:09

Mikkel