ScalaQuery multiple primary key & foreign key
Asked Answered
L

1

8

How do we define a multiple primary key and a foreign key in ScalaQuery?

object myTable1 extends Table([Int])("myTable1") {
  def id = column[Int]("id", O PrimaryKey)
  def * = id
}    

object myTable2 extends Table([Int, Int, Int])("myTable2") {
  def pk1 = column[Int]("id1")
  def pk2 = column[Int]("id2")
  def fk1 = column[Int]("fk1")
  def * = pk1 ~ pk2 ~ fk1
}

So what is the code to use if I want pk1 and pk2 in myTable2 to be the primary key and fk1 in myTable2 to refer to id in myTable1?

Lantha answered 18/3, 2011 at 3:16 Comment(0)
S
8

The following should work against the ScalaQuery master branch:

object myTable2 extends Table([Int, Int, Int])("myTable2") {
  def pk1 = column[Int]("id1")
  def pk2 = column[Int]("id2")
  def fk1 = column[Int]("fk1")
  def * = pk1 ~ pk2 ~ fk1
  def pk = primaryKey("pk_myTable2", pk1 ~ pk2)
  def fkMyTable1 = foreignKey("myTable1_fk", fk1, myTable1)(_.id)
}

While fk1 in myTable2 is the underlying column, fkMyTable1 is the foreign key definition which doubles as a join on the foreign key. Foreign keys are available in ScalaQuery 0.9.1, explicit primary keys (with names and with support for multiple columns) are available in master at the moment and will be included in 0.9.2. You can find more examples in the unit test classes ForeignKeyTest and PrimaryKeyTest.

Sericeous answered 18/3, 2011 at 16:59 Comment(1)
thanks for the reply. Any idea on when 0.9.2 will be released? I am using SBT with ScalaQuery so I am not thinking of using the master build.Lantha

© 2022 - 2024 — McMap. All rights reserved.