Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ScalaQuery multiple primary key & foreign key

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?

like image 718
JohanSJA Avatar asked Mar 18 '11 03:03

JohanSJA


1 Answers

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.

like image 138
szeiger Avatar answered Oct 17 '22 15:10

szeiger