0

I want to add foreign key constraint in one of my model of Play2 Framework with Slick 2. Referring to document Slick2-Mapping-Configuration

Suppose, I have two models defined in two scala files: Person and Address inside models directory.

Using the code reference in document will not help because both class lies in separate file. How would I declare foreign key on Person to Address? Any code reference will be more helpful.

Thanks

Peter
  • 7,020
  • 4
  • 31
  • 51
surenyonjan
  • 2,097
  • 3
  • 17
  • 26
  • What is the problem? As long as the classes are in the same package, they still can refer to each other. – Ashalynd Jan 12 '15 at 00:06

1 Answers1

0

Assuming that both your classes are located in the same package, this code should work:

<Person.scala>
package the.package.name

type Person = (Int,String,Int,Int)
class People(tag: Tag) extends Table[Person](tag, "PERSON") {
  def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
  def name = column[String]("NAME")
  def age = column[Int]("AGE")
  def addressId = column[Int]("ADDRESS_ID")
  def * = (id,name,age,addressId)
  def address = foreignKey("ADDRESS",addressId,addresses)(_.id)
}

object people extends TableQuery(new People(_)) {
  val findByName = this.findBy(_.name)
  // more methods there
}


<Address.scala>
package the.package.name

type Address = (Int,String,String)
class Addresses(tag: Tag) extends Table[Address](tag, "ADDRESS") {
  def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
  def street = column[String]("STREET")
  def city = column[String]("CITY")
  def * = (id,street,city)
}

object addresses extends TableQuery(new Addresses(_)) {
  val findByName = this.findBy(_.name)
  // more methods there
}
Ashalynd
  • 12,363
  • 2
  • 34
  • 37